nicoboou commited on
Commit
363ae52
·
verified ·
1 Parent(s): 1119359

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +25 -0
  3. config_chada_vit.py +34 -0
  4. model.safetensors +3 -0
  5. modeling_chada_vit.py +424 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChAdaViTModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "config_chada_vit.ChAdaViTConfig",
7
+ "AutoModel": "modeling_chada_vit.ChAdaViTModel"
8
+ },
9
+ "depth": 12,
10
+ "drop_path_rate": 0.0,
11
+ "drop_rate": 0.0,
12
+ "embed_dim": 192,
13
+ "img_size": [
14
+ 224
15
+ ],
16
+ "in_chans": 1,
17
+ "max_number_channels": 10,
18
+ "model_type": "chadavit",
19
+ "num_classes": 0,
20
+ "num_heads": 12,
21
+ "patch_size": 16,
22
+ "return_all_tokens": false,
23
+ "torch_dtype": "float32",
24
+ "transformers_version": "4.39.3"
25
+ }
config_chada_vit.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List
3
+
4
+
5
+ class ChAdaViTConfig(PretrainedConfig):
6
+ model_type = "chadavit"
7
+
8
+ def __init__(
9
+ self,
10
+ img_size: List[int] = [224],
11
+ in_chans: int = 1,
12
+ embed_dim: int = 192,
13
+ patch_size: int = 16,
14
+ num_classes: int = 0,
15
+ depth: int = 12,
16
+ num_heads: int = 12,
17
+ drop_rate: float = 0.0,
18
+ drop_path_rate: float = 0.0,
19
+ return_all_tokens: bool = True,
20
+ max_number_channels: int = 10,
21
+ **kwargs,
22
+ ):
23
+ self.img_size = img_size
24
+ self.in_chans = in_chans
25
+ self.embed_dim = embed_dim
26
+ self.patch_size = patch_size
27
+ self.num_classes = num_classes
28
+ self.depth = depth
29
+ self.num_heads = num_heads
30
+ self.drop_rate = drop_rate
31
+ self.drop_path_rate = drop_path_rate
32
+ self.return_all_tokens = return_all_tokens
33
+ self.max_number_channels = max_number_channels
34
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e3abb79d96d8a15785470441cb68bd8ff8dca2cc04e976e567fb58f7b542f8a
3
+ size 45380728
modeling_chada_vit.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ChAda-ViT (i.e Channel Adaptive ViT) is a variant of ViT that can handle multi-channel images.
3
+ """
4
+
5
+ import math
6
+ from functools import partial
7
+ from typing import Optional, Union, Callable
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers import PreTrainedModel
12
+
13
+ from torch import Tensor
14
+ import torch.nn.functional as F
15
+ from torch.nn.modules.module import Module
16
+ from torch.nn.modules.activation import MultiheadAttention
17
+ from torch.nn.modules.dropout import Dropout
18
+ from torch.nn.modules.linear import Linear
19
+ from torch.nn.modules.normalization import LayerNorm
20
+
21
+ from chada_vit.utils.misc import trunc_normal_
22
+ from chada_vit.config_chada_vit import ChAdaViTConfig
23
+
24
+
25
+ def _get_activation_fn(activation: str) -> Callable[[Tensor], Tensor]:
26
+ if activation == "relu":
27
+ return F.relu
28
+ elif activation == "gelu":
29
+ return F.gelu
30
+
31
+ raise RuntimeError("activation should be relu/gelu, not {}".format(activation))
32
+
33
+
34
+ class TransformerEncoderLayer(Module):
35
+ r"""
36
+ Mostly copied from torch.nn.TransformerEncoderLayer, but with the following changes:
37
+ - Added the possibility to retrieve the attention weights
38
+ """
39
+
40
+ __constants__ = ["batch_first", "norm_first"]
41
+
42
+ def __init__(
43
+ self,
44
+ d_model: int,
45
+ nhead: int,
46
+ dim_feedforward: int = 2048,
47
+ dropout: float = 0.1,
48
+ activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
49
+ layer_norm_eps: float = 1e-5,
50
+ batch_first: bool = False,
51
+ norm_first: bool = False,
52
+ device=None,
53
+ dtype=None,
54
+ ) -> None:
55
+ factory_kwargs = {"device": device, "dtype": dtype}
56
+ super(TransformerEncoderLayer, self).__init__()
57
+ self.self_attn = MultiheadAttention(
58
+ embed_dim=d_model,
59
+ num_heads=nhead,
60
+ dropout=dropout,
61
+ batch_first=batch_first,
62
+ **factory_kwargs,
63
+ )
64
+ # Implementation of Feedforward model
65
+ self.linear1 = Linear(d_model, dim_feedforward, **factory_kwargs)
66
+ self.dropout = Dropout(dropout)
67
+ self.linear2 = Linear(dim_feedforward, d_model, **factory_kwargs)
68
+
69
+ self.norm_first = norm_first
70
+ self.norm1 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
71
+ self.norm2 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
72
+ self.dropout1 = Dropout(dropout)
73
+ self.dropout2 = Dropout(dropout)
74
+
75
+ # Legacy string support for activation function.
76
+ if isinstance(activation, str):
77
+ activation = _get_activation_fn(activation)
78
+
79
+ # We can't test self.activation in forward() in TorchScript,
80
+ # so stash some information about it instead.
81
+ if activation is F.relu:
82
+ self.activation_relu_or_gelu = 1
83
+ elif activation is F.gelu:
84
+ self.activation_relu_or_gelu = 2
85
+ else:
86
+ self.activation_relu_or_gelu = 0
87
+ self.activation = activation
88
+
89
+ def __setstate__(self, state):
90
+ super(TransformerEncoderLayer, self).__setstate__(state)
91
+ if not hasattr(self, "activation"):
92
+ self.activation = F.relu
93
+
94
+ def forward(
95
+ self,
96
+ src: Tensor,
97
+ src_mask: Optional[Tensor] = None,
98
+ src_key_padding_mask: Optional[Tensor] = None,
99
+ return_attention=False,
100
+ ) -> Tensor:
101
+ r"""Pass the input through the encoder layer.
102
+
103
+ Args:
104
+ src: the sequence to the encoder layer (required).
105
+ src_mask: the mask for the src sequence (optional).
106
+ src_key_padding_mask: the mask for the src keys per batch (optional).
107
+
108
+ Shape:
109
+ see the docs in Transformer class.
110
+ """
111
+
112
+ x = src
113
+ if self.norm_first:
114
+ attn, attn_weights = self._sa_block(
115
+ x=self.norm1(x),
116
+ attn_mask=src_mask,
117
+ key_padding_mask=src_key_padding_mask,
118
+ return_attention=return_attention,
119
+ )
120
+ if return_attention:
121
+ return attn_weights
122
+ x = x + attn
123
+ x = x + self._ff_block(self.norm2(x))
124
+ else:
125
+ attn, attn_weights = self._sa_block(
126
+ x=self.norm1(x),
127
+ attn_mask=src_mask,
128
+ key_padding_mask=src_key_padding_mask,
129
+ return_attention=return_attention,
130
+ )
131
+ if return_attention:
132
+ return attn_weights
133
+ x = self.norm1(x + attn)
134
+ x = self.norm2(x + self._ff_block(x))
135
+
136
+ return x
137
+
138
+ # self-attention block
139
+ def _sa_block(
140
+ self,
141
+ x: Tensor,
142
+ attn_mask: Optional[Tensor],
143
+ key_padding_mask: Optional[Tensor],
144
+ return_attention: bool = False,
145
+ ) -> Tensor:
146
+ x, attn_weights = self.self_attn(
147
+ x,
148
+ x,
149
+ x,
150
+ attn_mask=attn_mask,
151
+ key_padding_mask=key_padding_mask,
152
+ need_weights=return_attention,
153
+ average_attn_weights=False,
154
+ )
155
+ return self.dropout1(x), attn_weights
156
+
157
+ # feed forward block
158
+ def _ff_block(self, x: Tensor) -> Tensor:
159
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
160
+ return self.dropout2(x)
161
+
162
+
163
+ class TokenLearner(nn.Module):
164
+ """Image to Patch Embedding"""
165
+
166
+ def __init__(self, img_size=224, patch_size=16, in_chans=1, embed_dim=768):
167
+ super().__init__()
168
+ num_patches = (img_size // patch_size) * (img_size // patch_size)
169
+ self.img_size = img_size
170
+ self.patch_size = patch_size
171
+ self.num_patches = num_patches
172
+
173
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
174
+
175
+ def forward(self, x):
176
+ x = self.proj(x)
177
+ x = x.flatten(2)
178
+ x = x.transpose(1, 2)
179
+ return x
180
+
181
+
182
+ class ChAdaViTModel(PreTrainedModel):
183
+ """Channel Adaptive Vision Transformer"""
184
+
185
+ config_class = ChAdaViTConfig
186
+
187
+ def __init__(self, config):
188
+ super().__init__(config)
189
+
190
+ # Embeddings dimension
191
+ self.num_features = self.embed_dim = config.embed_dim
192
+
193
+ # Num of maximum channels in the batch
194
+ self.max_channels = config.max_number_channels
195
+
196
+ # Tokenization module
197
+ self.token_learner = TokenLearner(
198
+ img_size=config.img_size[0],
199
+ patch_size=config.patch_size,
200
+ in_chans=config.in_chans,
201
+ embed_dim=self.embed_dim,
202
+ )
203
+ num_patches = self.token_learner.num_patches
204
+
205
+ self.cls_token = nn.Parameter(
206
+ torch.zeros(1, 1, self.embed_dim)
207
+ ) # (B, max_channels * num_tokens, embed_dim)
208
+ self.channel_token = nn.Parameter(
209
+ torch.zeros(1, self.max_channels, 1, self.embed_dim)
210
+ ) # (B, max_channels, 1, embed_dim)
211
+ self.pos_embed = nn.Parameter(
212
+ torch.zeros(1, 1, num_patches + 1, self.embed_dim)
213
+ ) # (B, max_channels, num_tokens, embed_dim)
214
+ self.pos_drop = nn.Dropout(p=config.drop_rate)
215
+
216
+ # TransformerEncoder block
217
+ dpr = [
218
+ x.item() for x in torch.linspace(0, config.drop_path_rate, config.depth)
219
+ ] # stochastic depth decay rule
220
+ self.blocks = nn.ModuleList(
221
+ [
222
+ TransformerEncoderLayer(
223
+ d_model=self.embed_dim,
224
+ nhead=config.num_heads,
225
+ dim_feedforward=2048,
226
+ dropout=dpr[i],
227
+ batch_first=True,
228
+ )
229
+ for i in range(config.depth)
230
+ ]
231
+ )
232
+ self.norm = nn.LayerNorm(self.embed_dim)
233
+
234
+ # Classifier head
235
+ self.head = nn.Linear(self.embed_dim, config.num_classes) if config.num_classes > 0 else nn.Identity()
236
+
237
+ # Return only the [CLS] token or all tokens
238
+ self.return_all_tokens = config.return_all_tokens
239
+
240
+ trunc_normal_(self.pos_embed, std=0.02)
241
+ trunc_normal_(self.cls_token, std=0.02)
242
+ trunc_normal_(self.channel_token, std=0.02)
243
+ self.apply(self._init_weights)
244
+
245
+ def _init_weights(self, m):
246
+ if isinstance(m, nn.Linear):
247
+ trunc_normal_(m.weight, std=0.02)
248
+ if isinstance(m, nn.Linear) and m.bias is not None:
249
+ nn.init.constant_(m.bias, 0)
250
+ elif isinstance(m, nn.LayerNorm):
251
+ nn.init.constant_(m.bias, 0)
252
+ nn.init.constant_(m.weight, 1.0)
253
+
254
+ def add_pos_encoding_per_channel(self, x, w, h, class_pos_embed: bool = False):
255
+ """
256
+ Adds num_patches positional embeddings to EACH of the channels.
257
+ """
258
+ npatch = x.shape[2]
259
+ N = self.pos_embed.shape[2] - 1
260
+
261
+ # --------------------- [CLS] positional encoding --------------------- #
262
+ if class_pos_embed:
263
+ return self.pos_embed[:, :, 0]
264
+
265
+ # --------------------- Patches positional encoding --------------------- #
266
+ # If the input size is the same as the training size, return the positional embeddings for the desired type
267
+ if npatch == N and w == h:
268
+ return self.pos_embed[:, :, 1:]
269
+
270
+ # Otherwise, interpolate the positional encoding for the input tokens
271
+ class_pos_embed = self.pos_embed[:, :, 0]
272
+ patch_pos_embed = self.pos_embed[:, :, 1:]
273
+ dim = x.shape[-1]
274
+ w0 = w // self.token_learner.patch_size
275
+ h0 = h // self.token_learner.patch_size
276
+ # a small number is added by DINO team to avoid floating point error in the interpolation
277
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
278
+ w0, h0 = w0 + 0.1, h0 + 0.1
279
+ patch_pos_embed = nn.functional.interpolate(
280
+ patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
281
+ scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
282
+ mode="bicubic",
283
+ )
284
+ assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
285
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
286
+ return patch_pos_embed.unsqueeze(0)
287
+
288
+ def channel_aware_tokenization(self, x, index, list_num_channels, max_channels=10):
289
+ B, nc, w, h = x.shape # (B*num_channels, 1, w, h)
290
+
291
+ # Tokenize through linear embedding
292
+ tokens_per_channel = self.token_learner(x)
293
+
294
+ # Concatenate tokens per channel in each image
295
+ chunks = torch.split(tokens_per_channel, list_num_channels[index], dim=0)
296
+
297
+ # Pad the tokens tensor with zeros for each image separately in the chunks list
298
+ padded_tokens = [
299
+ torch.cat(
300
+ [
301
+ chunk,
302
+ torch.zeros(
303
+ (max_channels - chunk.size(0), chunk.size(1), chunk.size(2)),
304
+ device=chunk.device,
305
+ ),
306
+ ],
307
+ dim=0,
308
+ )
309
+ if chunk.size(0) < max_channels
310
+ else chunk
311
+ for chunk in chunks
312
+ ]
313
+
314
+ # Stack along the batch dimension
315
+ padded_tokens = torch.stack(padded_tokens, dim=0)
316
+ num_tokens = padded_tokens.size(2)
317
+
318
+ # Reshape the patches embeddings on the channel dimension
319
+ padded_tokens = padded_tokens.reshape(padded_tokens.size(0), -1, padded_tokens.size(3))
320
+
321
+ # Compute the masking for avoiding self-attention on empty padded channels
322
+ channel_mask = torch.all(padded_tokens == 0.0, dim=-1)
323
+
324
+ # Destack to obtain the original number of channels
325
+ padded_tokens = padded_tokens.reshape(-1, max_channels, num_tokens, padded_tokens.size(-1))
326
+
327
+ # Add the [POS] token to the embed patch tokens
328
+ padded_tokens = padded_tokens + self.add_pos_encoding_per_channel(
329
+ padded_tokens, w, h, class_pos_embed=False
330
+ )
331
+
332
+ # Add the [CHANNEL] token to the embed patch tokens
333
+ if max_channels == self.max_channels:
334
+ channel_tokens = self.channel_token.expand(padded_tokens.shape[0], -1, padded_tokens.shape[2], -1)
335
+ padded_tokens = padded_tokens + channel_tokens
336
+
337
+ # Restack the patches embeddings on the channel dimension
338
+ embeddings = padded_tokens.reshape(padded_tokens.size(0), -1, padded_tokens.size(3))
339
+
340
+ # Expand the [CLS] token to the batch dimension
341
+ cls_tokens = self.cls_token.expand(embeddings.shape[0], -1, -1)
342
+
343
+ # Add [POS] positional encoding to the [CLS] token
344
+ cls_tokens = cls_tokens + self.add_pos_encoding_per_channel(embeddings, w, h, class_pos_embed=True)
345
+
346
+ # Concatenate the [CLS] token to the embed patch tokens
347
+ embeddings = torch.cat([cls_tokens, embeddings], dim=1)
348
+
349
+ # Adding a False value to the beginning of each channel_mask to account for the [CLS] token
350
+ channel_mask = torch.cat(
351
+ [
352
+ torch.tensor([False], device=channel_mask.device).expand(channel_mask.size(0), 1),
353
+ channel_mask,
354
+ ],
355
+ dim=1,
356
+ )
357
+
358
+ return self.pos_drop(embeddings), channel_mask
359
+
360
+ def forward(self, x, index, list_num_channels):
361
+ # Apply the TokenLearner module to obtain learnable tokens
362
+ x, channel_mask = self.channel_aware_tokenization(
363
+ x, index, list_num_channels
364
+ ) # (B*num_channels, embed_dim)
365
+
366
+ # Apply the self-attention layers with masked self-attention
367
+ for blk in self.blocks:
368
+ x = blk(
369
+ x, src_key_padding_mask=channel_mask
370
+ ) # Use src_key_padding_mask to mask out padded tokens
371
+
372
+ # Normalize
373
+ x = self.norm(x)
374
+
375
+ if self.return_all_tokens:
376
+ # Create a mask to select non-masked tokens (excluding CLS token)
377
+ non_masked_tokens_mask = ~channel_mask[:, 1:]
378
+ non_masked_tokens = x[:, 1:][non_masked_tokens_mask]
379
+ return non_masked_tokens # return non-masked tokens (excluding CLS token)
380
+ else:
381
+ return x[:, 0] # return only the [CLS] token
382
+
383
+ def channel_token_sanity_check(self, x):
384
+ """
385
+ Helper function to check consistency of channel tokens.
386
+ """
387
+ # 1. Compare Patches Across Different Channels
388
+ print("Values for the first patch across different channels:")
389
+ for ch in range(10): # Assuming 10 channels
390
+ print(f"Channel {ch + 1}:", x[0, ch, 0, :5]) # Print first 5 values of the embedding for brevity
391
+
392
+ print("\n")
393
+
394
+ # 2. Compare Patches Within the Same Channel
395
+ for ch in range(10):
396
+ is_same = torch.all(x[0, ch, 0] == x[0, ch, 1])
397
+ print(f"First and second patch embeddings are the same for Channel {ch + 1}: {is_same.item()}")
398
+
399
+ # 3. Check Consistency Across Batch
400
+ print("Checking consistency of channel tokens across the batch:")
401
+ for ch in range(10):
402
+ is_consistent = torch.all(x[0, ch, 0] == x[1, ch, 0])
403
+ print(
404
+ f"Channel token for first patch is consistent between first and second image for Channel {ch + 1}: {is_consistent.item()}"
405
+ )
406
+
407
+ def get_last_selfattention(self, x):
408
+ x, channel_mask = self.channel_aware_tokenization(x, index=0, list_num_channels=[1], max_channels=1)
409
+ for i, blk in enumerate(self.blocks):
410
+ if i < len(self.blocks) - 1:
411
+ x = blk(x, src_key_padding_mask=channel_mask)
412
+ else:
413
+ # return attention of the last block
414
+ return blk(x, src_key_padding_mask=channel_mask, return_attention=True)
415
+
416
+ def get_intermediate_layers(self, x, n=1):
417
+ x, channel_mask = self.channel_aware_tokenization(x)
418
+ # return the output tokens from the `n` last blocks
419
+ output = []
420
+ for i, blk in enumerate(self.blocks):
421
+ x = blk(x, src_key_padding_mask=channel_mask)
422
+ if len(self.blocks) - i <= n:
423
+ output.append(self.norm(x))
424
+ return output