Safetensors
tapct
custom_code
TimVeenboer commited on
Commit
16a53c5
·
1 Parent(s): 4d7f8cd

model commit

Browse files
README.md CHANGED
@@ -1,3 +1,43 @@
1
- ---
2
- license: cc-by-nc-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ ---
4
+
5
+ # TAP-CT: 3D Task-Agnostic Pretraining of CT Foundation Models
6
+
7
+ TAP-CT is a suite of foundation models for computed tomography (CT) imaging, pretrained in a task-agnostic manner through an adaptation of DINOv2 for volumetric data. These models learn robust 3D representations from CT scans without requiring task-specific annotations.
8
+
9
+ This repository provides TAP-CT-S-2D, a Vision Transformer (ViT-Small) architecture pretrained on volumetric inputs with a spatial resolution of (224, 224) and a patch size of (16, 16). For inference on full-resolution CT volumes, a sliding window approach can be employed to extract features across the entire scan. Additional TAP-CT model variants, as well as the image processor, will be released in future updates.
10
+
11
+ ## Preprocessing
12
+
13
+ While a dedicated image processor will be released in future updates, optimal feature extraction requires the following preprocessing pipeline:
14
+
15
+ 1. **Orientation**: Convert the volume to LPS (Left-Posterior-Superior) orientation. While the model is likely orientation-invariant, all evaluations were conducted using LPS orientation.
16
+ 2. **Spatial Resizing**: Resize the volume to a spatial resolution of \(z, 224, 224\) or \(z, 512, 512\), where \(z\) represents the number of slices along the axial dimension.
17
+ 3. **Intensity Clipping**: Clip voxel intensities to the range \([-1008, 822]\) HU (Hounsfield Units).
18
+ 4. **Normalization**: Apply z-score normalization using \(mean = -86.8086\) and \(std = 322.6347\).
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ import torch
24
+ from transformers import AutoModel
25
+
26
+ # Load the model
27
+ model = AutoModel.from_pretrained('fomofo/tap-ct-s-2d', trust_remote_code=True)
28
+
29
+ # Prepare input (batch_size, channels, height, width)
30
+ x = torch.randn((16, 1, 224, 224))
31
+
32
+ # Forward pass
33
+ output = model.forward(x)
34
+ ```
35
+
36
+ The model returns a `BaseModelOutputWithPooling` object from the transformers library. The `output.pooler_output` contains the pooled `[CLS]` token representation, while `output.last_hidden_state` contains the spatial patch token embeddings. To extract features from all intermediate transformer layers, pass `output_hidden_states=True` to the forward method.
37
+
38
+ ## Model Details
39
+
40
+ - **Model Type**: 3D CT Vision Foundation Model
41
+ - **Input Shape**: `(batch_size, 1, height, width)`
42
+ - **Example Input**: `(16, 1, 224, 224)` - batch of 16 CT slices at 224×224 resolution
43
+ - **License**: CC-BY-NC-4.0
attention.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ import logging
20
+ import os
21
+ import warnings
22
+ from typing import Optional
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ logger = logging.getLogger("dinov2")
28
+
29
+
30
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
31
+ try:
32
+ if XFORMERS_ENABLED:
33
+ from xformers.ops import memory_efficient_attention, unbind
34
+
35
+ XFORMERS_AVAILABLE = True
36
+ warnings.warn("xFormers is available (Attention)")
37
+ else:
38
+ warnings.warn("xFormers is disabled (Attention)")
39
+ raise ImportError
40
+ except ImportError:
41
+ XFORMERS_AVAILABLE = False
42
+ warnings.warn("xFormers is not available (Attention)")
43
+
44
+
45
+ class Attention(nn.Module):
46
+ """Multi-head self-attention module.
47
+
48
+ Parameters
49
+ ----------
50
+ dim : int
51
+ Dimension of the input features.
52
+ num_heads : int, optional
53
+ Number of attention heads, by default 8.
54
+ qkv_bias : bool, optional
55
+ Whether to add a bias to the query, key, and value projections, by default False.
56
+ proj_bias : bool, optional
57
+ Whether to add a bias to the output projection, by default True.
58
+ attn_drop : float, optional
59
+ Dropout rate for the attention weights, by default 0.0.
60
+ proj_drop : float, optional
61
+ Dropout rate for the output projection, by default 0.0.
62
+
63
+ Raises
64
+ ------
65
+ ValueError
66
+ If `dim` is not divisible by `num_heads`.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ dim: int,
72
+ num_heads: int = 8,
73
+ qkv_bias: bool = False,
74
+ proj_bias: bool = True,
75
+ attn_drop: float = 0.0,
76
+ proj_drop: float = 0.0,
77
+ ) -> None:
78
+ """Inits :class:`Attention`.
79
+
80
+ Parameters
81
+ ----------
82
+ dim : int
83
+ Dimension of the input features.
84
+ num_heads : int, optional
85
+ Number of attention heads, by default 8.
86
+ qkv_bias : bool, optional
87
+ Whether to add a bias to the query, key, and value projections, by default False.
88
+ proj_bias : bool, optional
89
+ Whether to add a bias to the output projection, by default True.
90
+ attn_drop : float, optional
91
+ Dropout rate for the attention weights, by default 0.0.
92
+ proj_drop : float, optional
93
+ Dropout rate for the output projection, by default 0.0.
94
+
95
+ Raises
96
+ ------
97
+ ValueError
98
+ If `dim` is not divisible by `num_heads`.
99
+ """
100
+ super().__init__()
101
+ if dim % num_heads != 0:
102
+ raise ValueError(f"dim {dim} should be divisible by num_heads {num_heads}.")
103
+ self.num_heads = num_heads
104
+ head_dim = dim // num_heads
105
+ self.scale = head_dim**-0.5
106
+
107
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
108
+ self.attn_drop = nn.Dropout(attn_drop)
109
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
110
+ self.proj_drop = nn.Dropout(proj_drop)
111
+
112
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
113
+ """Forward pass of :class:`Attention`.
114
+
115
+ Parameters
116
+ ----------
117
+ x : torch.Tensor
118
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
119
+ the feature dimension.
120
+
121
+ Returns
122
+ -------
123
+ torch.Tensor
124
+ Output tensor of shape (B, N, C) after applying multi-head self-attention.
125
+ """
126
+ B, N, C = x.shape
127
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
128
+
129
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
130
+ attn = q @ k.transpose(-2, -1)
131
+
132
+ attn = attn.softmax(dim=-1)
133
+ attn = self.attn_drop(attn)
134
+
135
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
136
+ x = self.proj(x)
137
+ x = self.proj_drop(x)
138
+ return x
139
+
140
+
141
+ class MemEffAttention(Attention):
142
+ """Memory-efficient multi-head self-attention module using xFormers.
143
+
144
+ Parameters
145
+ ----------
146
+ dim : int
147
+ Dimension of the input features.
148
+ num_heads : int, optional
149
+ Number of attention heads, by default 8.
150
+ qkv_bias : bool, optional
151
+ Whether to add a bias to the query, key, and value projections, by default False.
152
+ proj_bias : bool, optional
153
+ Whether to add a bias to the output projection, by default True.
154
+ attn_drop : float, optional
155
+ Dropout rate for the attention weights, by default 0.0.
156
+ proj_drop : float, optional
157
+ Dropout rate for the output projection, by default 0.0.
158
+
159
+ Raises
160
+ ------
161
+ ValueError
162
+ If `dim` is not divisible by `num_heads`.
163
+ """
164
+
165
+ def forward(self, x: torch.Tensor, attn_bias: Optional[torch.Tensor] = None) -> torch.Tensor:
166
+ """Forward pass of :class:`MemEffAttention`.
167
+
168
+ Parameters
169
+ ----------
170
+ x : torch.Tensor
171
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
172
+ the feature dimension.
173
+ attn_bias : Optional[torch.Tensor], optional
174
+ Attention bias tensor for memory-efficient attention, by default None.
175
+
176
+ Raises
177
+ ------
178
+ AssertionError
179
+ If xFormers is not available and `attn_bias` is provided.
180
+
181
+ Returns
182
+ -------
183
+ torch.Tensor
184
+ Output tensor of shape (B, N, C) after applying memory-efficient multi-head self-attention.
185
+ """
186
+ if not XFORMERS_AVAILABLE:
187
+ if attn_bias is not None:
188
+ raise AssertionError("xFormers is required for using nested tensors")
189
+ return super().forward(x)
190
+
191
+ B, N, C = x.shape
192
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
193
+
194
+ q, k, v = unbind(qkv, 2)
195
+
196
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
197
+ x = x.reshape([B, N, C])
198
+
199
+ x = self.proj(x)
200
+ x = self.proj_drop(x)
201
+ return x
config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "tapct",
3
+ "model_size": "small",
4
+ "model_variant": "2d",
5
+ "img_size": [224, 224],
6
+ "patch_size": [16, 16],
7
+ "in_chans": 1,
8
+ "num_register_tokens": 4,
9
+ "init_values": 1e-5,
10
+ "block_chunks": 0,
11
+ "architectures": ["TAPCTModel"],
12
+ "auto_map": {
13
+ "AutoConfig": "configuration_tapct.TAPCTConfig",
14
+ "AutoModel": "modeling_tapct.TAPCTModel"
15
+ }
16
+ }
17
+
configuration_tapct.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Literal
15
+ from transformers import PretrainedConfig
16
+
17
+ class TAPCTConfig(PretrainedConfig):
18
+ """
19
+ Configuration class for TAP-CT models.
20
+
21
+ Parameters
22
+ ----------
23
+ model_size : Literal['small', 'base'], default='base'
24
+ Size of the model ('small' or 'base')
25
+ model_variant : Literal['2d', '2.5d', '3d'], default='3d'
26
+ Variant of the model ('2d', '2.5d', or '3d')
27
+ img_size : int | tuple | list, default=224
28
+ Input image size. For 2D: int or tuple[int, int], for 3D: tuple[int, int, int]
29
+ patch_size : int | tuple | list, default=16
30
+ Patch size. For 2D: int or tuple[int, int], for 3D: tuple[int, int, int]
31
+ in_chans : int, default=1
32
+ Number of input channels (default: 1 for CT scans)
33
+ num_register_tokens : int, default=4
34
+ Number of register tokens
35
+ init_values : float | None, default=None
36
+ Layer scale init values
37
+ block_chunks : int, default=0
38
+ Number of block chunks for FSDP
39
+ """
40
+ model_type = "tapct"
41
+
42
+ def __init__(
43
+ self,
44
+ model_size: Literal['small', 'base'] = 'base',
45
+ model_variant: Literal['2d', '2.5d', '3d'] = '3d',
46
+ img_size: int | tuple | list = 224,
47
+ patch_size: int | tuple | list = 16,
48
+ in_chans: int = 1,
49
+ num_register_tokens: int = 4,
50
+ init_values: float | None = None,
51
+ block_chunks: int = 0,
52
+ **kwargs
53
+ ):
54
+ super().__init__(**kwargs)
55
+ self.model_size = model_size
56
+ self.model_variant = model_variant
57
+ self.img_size = img_size
58
+ self.patch_size = patch_size
59
+ self.in_chans = in_chans
60
+ self.num_register_tokens = num_register_tokens
61
+ self.init_values = init_values
62
+ self.block_chunks = block_chunks
drop_path.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ import torch
20
+ from torch import nn
21
+
22
+
23
+ def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
24
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
25
+
26
+ Parameters
27
+ ----------
28
+ x : torch.Tensor
29
+ Input tensor of shape (B, *) where B is the batch size and * is any number of additional dimensions.
30
+ drop_prob : float, optional
31
+ Probability of dropping a path, by default 0.0
32
+ training : bool, optional
33
+ Whether the model is in training mode, by default False. If False, no paths are dropped.
34
+
35
+ Returns
36
+ -------
37
+ torch.Tensor
38
+ Output tensor with the same shape as input x, with paths dropped according to drop_prob.
39
+ """
40
+ if drop_prob == 0.0 or not training:
41
+ return x
42
+ keep_prob = 1 - drop_prob
43
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
44
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
45
+ if keep_prob > 0.0:
46
+ random_tensor.div_(keep_prob)
47
+ output = x * random_tensor
48
+ return output
49
+
50
+
51
+ class DropPath(nn.Module):
52
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
53
+
54
+ Parameters
55
+ ----------
56
+ drop_prob : float, optional
57
+ Probability of dropping a path, by default None. If None, no paths are dropped.
58
+ If set to 0.0, it behaves like an identity function.
59
+ """
60
+
61
+ def __init__(self, drop_prob: float = 0.0) -> None:
62
+ """Inits :class:`DropPath`.
63
+
64
+ Parameters
65
+ ----------
66
+ drop_prob : float, optional
67
+ Probability of dropping a path, by default 0.0. If None, no paths are dropped.
68
+ If set to 0.0, it behaves like an identity function.
69
+ """
70
+ super().__init__()
71
+ self.drop_prob = drop_prob
72
+
73
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
74
+ """Forward pass of :class:`DropPath`.
75
+
76
+ Parameters
77
+ ----------
78
+ x : torch.Tensor
79
+ Input tensor of shape (B, *) where B is the batch size and * is any number of additional dimensions.
80
+
81
+ Returns
82
+ -------
83
+ torch.Tensor
84
+ Output tensor with the same shape as input x, with paths dropped according to drop_prob.
85
+ """
86
+ return drop_path(x, self.drop_prob, self.training)
helpers.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ def make_tuple(x: int | tuple, n: int) -> tuple:
15
+ """Convert an integer or a tuple to an n-tuple.
16
+
17
+ Parameters
18
+ ----------
19
+ x : int or tuple
20
+ Input value which can be an integer or a tuple of n integers.
21
+ n : int
22
+ The length of the tuple to return.
23
+
24
+ Returns
25
+ -------
26
+ tuple
27
+ A tuple of n integers.
28
+ """
29
+ if isinstance(x, tuple) or isinstance(x, list):
30
+ if len(x) != n:
31
+ raise ValueError(f"Expected a tuple of length {n}, got {len(x)}")
32
+ if not all(isinstance(i, int) for i in x):
33
+ raise ValueError("All elements in the tuple must be integers")
34
+ return tuple(x)
35
+
36
+ if not isinstance(x, int):
37
+ raise TypeError(f"Expected int, got {type(x)}")
38
+ return (x,) * n
39
+
40
+
41
+ def make_2tuple(x: int | tuple[int, int]) -> tuple[int, int]:
42
+ """Convert an integer or a tuple to a 2-tuple.
43
+
44
+ Parameters
45
+ ----------
46
+ x : int or tuple[int, int]
47
+ Input value which can be an integer or a tuple of two integers with two elements.
48
+
49
+ Returns
50
+ -------
51
+ tuple[int, int]
52
+ A tuple of two integers.
53
+ """
54
+ return make_tuple(x, 2)
55
+
56
+
57
+ def make_3tuple(x: int | tuple[int, int, int]) -> tuple[int, int, int]:
58
+ """Convert an integer or a tuple to a 3-tuple.
59
+
60
+ Parameters
61
+ ----------
62
+ x : int or tuple[int, int, int]
63
+ Input value which can be an integer or a tuple of three integers with three elements.
64
+
65
+ Returns
66
+ -------
67
+ tuple[int, int, int]
68
+ A tuple of three integers.
69
+ """
70
+ return make_tuple(x, 3)
layer_scale.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ from typing import Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+
25
+ class LayerScale(nn.Module):
26
+ """Layer scale module for scaling the output of a layer.
27
+
28
+ Parameters
29
+ ----------
30
+ dim : int
31
+ Dimension of the layer scale.
32
+ init_values : float or torch.Tensor, optional
33
+ Initial values for the layer scale, by default 1e-5. If a tensor is provided, it should have shape (dim,).
34
+ inplace : bool, optional
35
+ Whether to perform the operation in-place, by default False.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ dim: int,
41
+ init_values: Union[float, torch.Tensor] = 1e-5,
42
+ inplace: bool = False,
43
+ ) -> None:
44
+ """Inits :class:`LayerScale
45
+
46
+ Parameters
47
+ ----------
48
+ dim : int
49
+ Dimension of the layer scale.
50
+ init_values : float or torch.Tensor, optional
51
+ Initial values for the layer scale, by default 1e-5. If a tensor is provided, it should have shape (dim,).
52
+ inplace : bool, optional
53
+ Whether to perform the operation in-place, by default False.
54
+ """
55
+ super().__init__()
56
+
57
+ self.inplace = inplace
58
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
59
+
60
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
61
+ """Forward pass of :class:`LayerScale`.
62
+
63
+ Parameters
64
+ ----------
65
+ x : torch.Tensor
66
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
67
+ the feature dimension.
68
+
69
+ Returns
70
+ -------
71
+ torch.Tensor
72
+ Scaled output tensor of shape (B, N, C).
73
+ """
74
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
mlp.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ from typing import Callable, Optional
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+
25
+ class Mlp(nn.Module):
26
+ """Multi-layer perceptron (MLP) module.
27
+
28
+ Creates a simple MLP with two linear layers and an activation function in between and dropout after each layer.
29
+
30
+ Parameters
31
+ ----------
32
+ in_features : int
33
+ Number of input features.
34
+ hidden_features : int, optional
35
+ Number of hidden features, by default 4 * in_features.
36
+ out_features : int, optional
37
+ Number of output features, by default in_features.
38
+ act_layer : Callable[..., nn.Module], optional
39
+ Activation layer, by default nn.GELU.
40
+ drop : float, optional
41
+ Dropout rate, by default 0.0.
42
+ bias : bool, optional
43
+ Whether to use bias in the linear layers, by default True.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ in_features: int,
49
+ hidden_features: Optional[int] = None,
50
+ out_features: Optional[int] = None,
51
+ act_layer: Callable[..., nn.Module] = nn.GELU,
52
+ drop: float = 0.0,
53
+ bias: bool = True,
54
+ ) -> None:
55
+ """Inits :class:`Mlp`.
56
+
57
+ Parameters
58
+ ----------
59
+
60
+ in_features : int
61
+ Number of input features.
62
+ hidden_features : int, optional
63
+ Number of hidden features, by default 4 * in_features.
64
+ out_features : int, optional
65
+ Number of output features, by default in_features.
66
+ act_layer : Callable[..., nn.Module], optional
67
+ Activation layer, by default nn.GELU.
68
+ drop : float, optional
69
+ Dropout rate, by default 0.0.
70
+ bias : bool, optional
71
+ Whether to use bias in the linear layers, by default True.
72
+ """
73
+ super().__init__()
74
+
75
+ out_features = out_features or in_features
76
+ hidden_features = hidden_features or in_features
77
+
78
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
79
+ self.act = act_layer()
80
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
81
+ self.drop = nn.Dropout(drop)
82
+
83
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
84
+ """Forward pass of :class:`Mlp`.
85
+
86
+ Parameters
87
+ ----------
88
+ x : torch.Tensor
89
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
90
+ the feature dimension.
91
+
92
+ Returns
93
+ -------
94
+ torch.Tensor
95
+ Output tensor of shape (B, N, out_features) after applying the MLP.
96
+ """
97
+ x = self.fc1(x)
98
+ x = self.act(x)
99
+ x = self.drop(x)
100
+ x = self.fc2(x)
101
+ x = self.drop(x)
102
+ return x
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6b145206ed34228418d303833412f20da2e98b586c97f0b2139a48025c27851
3
+ size 85937736
modeling_tapct.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional
15
+ from transformers import PreTrainedModel
16
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
17
+ import torch
18
+
19
+ from .configuration_tapct import TAPCTConfig
20
+ from .vision_transformer import vit_small, vit_base
21
+ from .vision_transformer_3d import vit_3d_small, vit_3d_base
22
+ from .vision_transformer_base import DinoVisionTransformerBase
23
+
24
+ class TAPCTPreTrainedModel(PreTrainedModel):
25
+ config_class = TAPCTConfig
26
+ base_model_prefix = "tapct"
27
+
28
+
29
+ class TAPCTModel(TAPCTPreTrainedModel):
30
+ """
31
+ TAP-CT Vision Transformer model based on DINOv2: https://github.com/facebookresearch/dinov2.
32
+
33
+ This model outputs raw hidden states and does not include any task-specific head.
34
+ """
35
+
36
+ def __init__(self, config: TAPCTConfig) -> None:
37
+ super().__init__(config)
38
+ self.config = config
39
+ self.model: DinoVisionTransformerBase
40
+
41
+ match config.model_variant:
42
+ case "2d":
43
+ if config.model_size == "small":
44
+ self.model = vit_small(
45
+ img_size=config.img_size,
46
+ patch_size=config.patch_size,
47
+ num_register_tokens=config.num_register_tokens,
48
+ in_chans=config.in_chans,
49
+ init_values=config.init_values,
50
+ block_chunks=config.block_chunks
51
+ )
52
+ elif config.model_size == "base":
53
+ self.model = vit_base(
54
+ img_size=config.img_size,
55
+ patch_size=config.patch_size,
56
+ num_register_tokens=config.num_register_tokens,
57
+ in_chans=config.in_chans,
58
+ init_values=config.init_values,
59
+ block_chunks=config.block_chunks
60
+ )
61
+ else:
62
+ raise ValueError(f"Model size '{config.model_size}' not supported for 2D")
63
+
64
+ case "2.5d" | "3d":
65
+ if config.model_size == "small":
66
+ self.model = vit_3d_small(
67
+ img_size=config.img_size,
68
+ patch_size=config.patch_size,
69
+ num_register_tokens=config.num_register_tokens,
70
+ in_chans=config.in_chans,
71
+ init_values=config.init_values,
72
+ block_chunks=config.block_chunks
73
+ )
74
+ elif config.model_size == "base":
75
+ self.model = vit_3d_base(
76
+ img_size=config.img_size,
77
+ patch_size=config.patch_size,
78
+ num_register_tokens=config.num_register_tokens,
79
+ in_chans=config.in_chans,
80
+ init_values=config.init_values,
81
+ block_chunks=config.block_chunks
82
+ )
83
+ else:
84
+ raise ValueError(f"Model size '{config.model_size}' not supported for 3D")
85
+
86
+ case _:
87
+ raise ValueError(f"Model variant '{config.model_variant}' not supported. Use '2d', '2.5d', or '3d'.")
88
+
89
+ # Initialize weights
90
+ self.post_init()
91
+
92
+ def forward(
93
+ self,
94
+ pixel_values: torch.Tensor,
95
+ output_hidden_states: Optional[bool] = None,
96
+ return_dict: Optional[bool] = None,
97
+ ) -> BaseModelOutputWithPooling:
98
+ """
99
+ Forward pass of the TAP-CT model.
100
+
101
+ Parameters
102
+ ----------
103
+ pixel_values : torch.Tensor
104
+ Input images. Shape (B, C, H, W) for 2D or (B, C, D, H, W) for 3D
105
+ output_hidden_states : Optional[bool], optional
106
+ Whether to return hidden states from all layers
107
+ return_dict : Optional[bool], optional
108
+ Whether to return a ModelOutput instead of a plain tuple
109
+
110
+ Returns
111
+ -------
112
+ BaseModelOutputWithPooling
113
+ Contains:
114
+ - last_hidden_state: Patch token features from the last layer
115
+ - pooler_output: CLS token from the last layer
116
+ - hidden_states: (optional) All hidden states if output_hidden_states=True
117
+ """
118
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
119
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
120
+
121
+ if output_hidden_states:
122
+ outputs_tuple = self.model.get_intermediate_layers(
123
+ pixel_values,
124
+ n=self.model.n_blocks,
125
+ return_class_token=True,
126
+ reshape=False
127
+ )
128
+ outputs = tuple(o[0] for o in outputs_tuple)
129
+ class_tokens = tuple(o[1] for o in outputs_tuple)
130
+
131
+ last_hidden_state = outputs[-1]
132
+ pooler_output = class_tokens[-1]
133
+ hidden_states = outputs
134
+ else:
135
+ outputs_tuple = self.model.get_intermediate_layers(
136
+ pixel_values,
137
+ n=1,
138
+ return_class_token=True,
139
+ reshape=False
140
+ )
141
+ last_hidden_state = outputs_tuple[0][0]
142
+ pooler_output = outputs_tuple[0][1]
143
+ hidden_states = None
144
+
145
+ if not return_dict:
146
+ return tuple(
147
+ v for v in [last_hidden_state, pooler_output, hidden_states]
148
+ if v is not None
149
+ )
150
+
151
+ return BaseModelOutputWithPooling(
152
+ last_hidden_state=last_hidden_state,
153
+ pooler_output=pooler_output,
154
+ hidden_states=hidden_states
155
+ )
patch_embed.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ from typing import Callable, Optional
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from .helpers import make_2tuple, make_3tuple
25
+
26
+
27
+ class PatchEmbed(nn.Module):
28
+ """Patch embedding layer for Vision Transformers for 2D images.
29
+
30
+ This layer divides the input image into patches and projects them into a higher-dimensional space.
31
+
32
+ Parameters
33
+ ----------
34
+ img_size : int or tuple[int, int], optional
35
+ Size of the input image. If an integer is provided, it is assumed to be square (img_size, img_size).
36
+ If a tuple is provided, it should be of the form (height, width), by default 224.
37
+ patch_size : int or tuple[int, int], optional
38
+ Size of the patches to be extracted from the input image. If an integer is provided, it is assumed to be square
39
+ (patch_size, patch_size). If a tuple is provided, it should be of the form (height, width), by default 16.
40
+ in_chans : int, optional
41
+ Number of input channels in the image, by default 3 (for RGB images).
42
+ embed_dim : int, optional
43
+ Dimension of the embedding space to which the patches will be projected, by default 768.
44
+ norm_layer : Callable, optional
45
+ Normalization layer to apply to the embeddings, by default None. If None, no normalization is applied.
46
+ flatten_embedding : bool, optional
47
+ Whether to flatten the embedding output, by default True.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ img_size: int | tuple[int, int] = 224,
53
+ patch_size: int | tuple[int, int] = 16,
54
+ in_chans: int = 3,
55
+ embed_dim: int = 768,
56
+ norm_layer: Optional[Callable] = None,
57
+ flatten_embedding: bool = True,
58
+ ) -> None:
59
+ """Inits :class:`PatchEmbed`.
60
+
61
+ Parameters
62
+ ----------
63
+ img_size : int or tuple[int, int], optional
64
+ Size of the input image. If an integer is provided, it is assumed to be square (img_size, img_size).
65
+ If a tuple is provided, it should be of the form (height, width), by default 224.
66
+ patch_size : int or tuple[int, int], optional
67
+ Size of the patches to be extracted from the input image. If an integer is provided, it is assumed to be square
68
+ (patch_size, patch_size). If a tuple is provided, it should be of the form (height, width), by default 16.
69
+ in_chans : int, optional
70
+ Number of input channels in the image, by default 3 (for RGB images).
71
+ embed_dim : int, optional
72
+ Dimension of the embedding space to which the patches will be projected, by default 768.
73
+ norm_layer : Callable, optional
74
+ Normalization layer to apply to the embeddings, by default None. If None, no normalization is applied.
75
+ flatten_embedding : bool, optional
76
+ Whether to flatten the embedding output, by default True.
77
+ """
78
+ super().__init__()
79
+
80
+ image_HW = make_2tuple(img_size)
81
+ patch_HW = make_2tuple(patch_size)
82
+ patch_grid_size = (
83
+ image_HW[0] // patch_HW[0],
84
+ image_HW[1] // patch_HW[1],
85
+ )
86
+
87
+ self.img_size = image_HW
88
+ self.patch_size = patch_HW
89
+ self.patches_resolution = patch_grid_size
90
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
91
+
92
+ self.in_chans = in_chans
93
+ self.embed_dim = embed_dim
94
+
95
+ self.flatten_embedding = flatten_embedding
96
+
97
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
98
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
99
+
100
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
101
+ """Forward pass of :class:`PatchEmbed`.
102
+
103
+ Parameters
104
+ ----------
105
+ x : torch.Tensor
106
+ Input tensor of shape (B, C, H, W) where B is the batch size, C is the number of channels,
107
+ H is the height, and W is the width of the input image.
108
+
109
+ Raises
110
+ ------
111
+ ValueError
112
+ If the input image dimensions are not compatible with the patch size.
113
+ """
114
+ _, _, H, W = x.shape
115
+ patch_H, patch_W = self.patch_size
116
+ if H % patch_H != 0:
117
+ raise ValueError(f"Input image height {H} is not a multiple of patch height {patch_H}")
118
+ if W % patch_W != 0:
119
+ raise ValueError(f"Input image width {W} is not a multiple of patch width: {patch_W}")
120
+
121
+ x = self.proj(x) # B C H W
122
+ H, W = x.size(2), x.size(3)
123
+ x = x.flatten(2).transpose(1, 2) # B HW C
124
+
125
+ x = self.norm(x)
126
+ if not self.flatten_embedding:
127
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
128
+ return x
129
+
130
+ def flops(self) -> float:
131
+ """Calculate the number of floating point operations (FLOPs) for the patch embedding layer.
132
+
133
+ Returns
134
+ -------
135
+ float
136
+ The number of FLOPs for the patch embedding layer.
137
+ """
138
+ Ho, Wo = self.patches_resolution
139
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
140
+ if not isinstance(self.norm, nn.Identity):
141
+ flops += Ho * Wo * self.embed_dim
142
+ return flops
143
+
144
+
145
+ class PatchEmbed3d(nn.Module):
146
+ """Patch embedding layer for Vision Transformers for 3D images.
147
+
148
+ This layer divides the input 3D image volume into patches and projects them into a higher-dimensional space.
149
+
150
+ Parameters
151
+ ----------
152
+ img_size : int or tuple[int, int, int], optional
153
+ Size of the input image volume. If an integer is provided, it is assumed to be cubic (img_size, img_size, img_size).
154
+ If a tuple is provided, it should be of the form (depth, height, width), by default 224.
155
+ patch_size : int or tuple[int, int, int], optional
156
+ Size of the patches to be extracted from the input image volume. If an integer is provided, it is assumed to be cubic
157
+ (patch_size, patch_size, patch_size). If a tuple is provided, it should be of the form (depth, height, width), by default 16.
158
+ in_chans : int, optional
159
+ Number of input channels in the image volume, by default 3 (for RGB images).
160
+ embed_dim : int, optional
161
+ Dimension of the embedding space to which the patches will be projected, by default 768.
162
+ norm_layer : Callable, optional
163
+ Normalization layer to apply to the embeddings, by default None. If None, no normalization is applied.
164
+ flatten_embedding : bool, optional
165
+ Whether to flatten the embedding output, by default True.
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ img_size: int | tuple[int, int, int] = 224,
171
+ patch_size: int | tuple[int, int, int] = 16,
172
+ in_chans: int = 3,
173
+ embed_dim: int = 768,
174
+ norm_layer: Optional[Callable] = None,
175
+ flatten_embedding: bool = True,
176
+ ) -> None:
177
+ """Inits :class:`PatchEmbed3d`.
178
+
179
+ Parameters
180
+ ----------
181
+ img_size : int or tuple[int, int, int], optional
182
+ Size of the input image volume. If an integer is provided, it is assumed to be cubic
183
+ (img_size, img_size, img_size).
184
+ If a tuple is provided, it should be of the form (depth, height, width), by default 224.
185
+ patch_size : int or tuple[int, int, int], optional
186
+ Size of the patches to be extracted from the input image volume. If an integer is provided, it is
187
+ assumed to be cubic (patch_size, patch_size, patch_size). If a tuple is provided, it should be of the
188
+ form (depth, height, width), by default 16.
189
+ in_chans : int, optional
190
+ Number of input channels in the image volume, by default 3 (for RGB images).
191
+ embed_dim : int, optional
192
+ Dimension of the embedding space to which the patches will be projected, by default 768.
193
+ norm_layer : Callable, optional
194
+ Normalization layer to apply to the embeddings, by default None. If None, no normalization is applied.
195
+ flatten_embedding : bool, optional
196
+ Whether to flatten the embedding output, by default True.
197
+ """
198
+ super().__init__()
199
+
200
+ image_DHW = make_3tuple(img_size)
201
+ patch_DHW = make_3tuple(patch_size)
202
+
203
+ patch_grid_size = (
204
+ image_DHW[0] // patch_DHW[0],
205
+ image_DHW[1] // patch_DHW[1],
206
+ image_DHW[2] // patch_DHW[2],
207
+ )
208
+
209
+ self.img_size = image_DHW
210
+ self.patch_size = patch_DHW
211
+ self.patches_resolution = patch_grid_size
212
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1] * patch_grid_size[2]
213
+
214
+ self.in_chans = in_chans
215
+ self.embed_dim = embed_dim
216
+
217
+ self.flatten_embedding = flatten_embedding
218
+ self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_DHW, stride=patch_DHW)
219
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
220
+
221
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
222
+ """Forward pass of :class:`PatchEmbed3d`.
223
+
224
+ Parameters
225
+ ----------
226
+ x : torch.Tensor
227
+ Input tensor of shape (B, C, D, H, W) where B is the batch size, C is the number of channels,
228
+ D is the depth, H is the height, and W is the width of the input volume.
229
+
230
+ Raises
231
+ ------
232
+ ValueError
233
+ If the input volume dimensions are not compatible with the patch size.
234
+ """
235
+ _, _, D, H, W = x.shape
236
+ patch_D, patch_H, patch_W = self.patch_size
237
+ if D % patch_D != 0:
238
+ raise ValueError(f"Input volume depth {D} is not a multiple of patch depth {patch_D}")
239
+ if H % patch_H != 0:
240
+ raise ValueError(f"Input volume height {H} is not a multiple of patch height {patch_H}")
241
+ if W % patch_W != 0:
242
+ raise ValueError(f"Input volume width {W} is not a multiple of patch width {patch_W}")
243
+
244
+ x = self.proj(x) # B C D H W
245
+ D, H, W = x.size(2), x.size(3), x.size(4)
246
+ x = x.flatten(2).transpose(1, 2) # B (DHW) C
247
+
248
+ x = self.norm(x)
249
+ if not self.flatten_embedding:
250
+ x = x.reshape(-1, D, H, W, self.embed_dim) # B D H W C
251
+ return x
252
+
253
+ def flops(self) -> float:
254
+ """Calculate the number of floating point operations (FLOPs) for the patch embedding 3D layer.
255
+
256
+ Returns
257
+ -------
258
+ float
259
+ The number of FLOPs for the patch embedding layer.
260
+ """
261
+ Do, Ho, Wo = self.patches_resolution
262
+ flops = (
263
+ Do
264
+ * Ho
265
+ * Wo
266
+ * self.embed_dim
267
+ * self.in_chans
268
+ * (self.patch_size[0] * self.patch_size[1] * self.patch_size[2])
269
+ )
270
+ if not isinstance(self.norm, nn.Identity):
271
+ flops += Do * Ho * Wo * self.embed_dim
272
+ return flops
swiglu_ffn.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ import os
20
+ import warnings
21
+ from typing import Callable, Optional
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ from torch import nn
26
+
27
+
28
+ class SwiGLUFFN(nn.Module):
29
+ r"""SwiGLU Feed-Forward Network (FFN) layer.
30
+
31
+ SwiGLU Feed-Forward Network (FFN) layer.
32
+
33
+ This module applies a two-layer position-wise feed-forward transformation with a SwiGLU activation:
34
+ a gated unit combining the SiLU nonlinearity with an elementwise multiplication.
35
+
36
+ Given input tensor ``x`` of shape ``(B, d)``, the computation is:
37
+
38
+ .. math::
39
+
40
+ [z_1, z_2] = x W_{12} + b_{12} \\\\
41
+ h = \mathrm{SiLU}(z_1) \odot z_2 \\\\
42
+ y = h W_3 + b_3
43
+
44
+ where:
45
+ - :math:`W_{12} \in \mathbb{R}^{d \times 2h}`, :math:`b_{12} \in \mathbb{R}^{2h}`
46
+ - :math:`W_3 \in \mathbb{R}^{h \times d_{\text{out}}}`, :math:`b_3 \in \mathbb{R}^{d_{\text{out}}}`
47
+ - :math:`\mathrm{SiLU}(x) = x \cdot \sigma(x)` is the Sigmoid Linear Unit
48
+ - :math:`\odot` denotes elementwise multiplication
49
+
50
+ Parameters
51
+ ----------
52
+ in_features : int
53
+ Input feature dimensionality (d).
54
+ hidden_features : int, optional
55
+ Hidden layer dimensionality (h). Defaults to in_features.
56
+ out_features : int, optional
57
+ Output feature dimensionality (d_out). Defaults to in_features.
58
+ act_layer : Callable[..., nn.Module], optional
59
+ Unused. Included for compatibility.
60
+ drop : float, optional
61
+ Dropout rate (unused).
62
+ bias : bool, optional
63
+ Whether to include bias terms in linear layers.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ in_features: int,
69
+ hidden_features: Optional[int] = None,
70
+ out_features: Optional[int] = None,
71
+ act_layer: Callable[..., nn.Module] = None,
72
+ drop: float = 0.0,
73
+ bias: bool = True,
74
+ ) -> None:
75
+ """Inits :class:`SwiGLUFFN`.
76
+
77
+ Parameters
78
+ ----------
79
+ in_features : int
80
+ Input feature dimensionality (d).
81
+ hidden_features : int, optional
82
+ Hidden layer dimensionality (h). Defaults to in_features.
83
+ out_features : int, optional
84
+ Output feature dimensionality (d_out). Defaults to in_features.
85
+ act_layer : Callable[..., nn.Module], optional
86
+ Unused. Included for compatibility.
87
+ drop : float, optional
88
+ Dropout rate (unused).
89
+ bias : bool, optional
90
+ Whether to include bias terms in linear layers.
91
+ """
92
+ super().__init__()
93
+ out_features = out_features or in_features
94
+ hidden_features = hidden_features or in_features
95
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
96
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
97
+
98
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
99
+ """Forward pass of :class:`SwiGLUFFN`.
100
+
101
+ Parameters
102
+ ----------
103
+ x : torch.Tensor
104
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
105
+ the input feature dimension.
106
+
107
+ Returns
108
+ -------
109
+ torch.Tensor
110
+ Output tensor of shape (B, N, out_features) after applying the SwiGLU feed-forward network.
111
+ """
112
+ x12 = self.w12(x)
113
+ x1, x2 = x12.chunk(2, dim=-1)
114
+ hidden = F.silu(x1) * x2
115
+ return self.w3(hidden)
116
+
117
+
118
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
119
+ try:
120
+ if XFORMERS_ENABLED:
121
+ from xformers.ops import SwiGLU
122
+
123
+ XFORMERS_AVAILABLE = True
124
+ warnings.warn("xFormers is available (SwiGLU)")
125
+ else:
126
+ warnings.warn("xFormers is disabled (SwiGLU)")
127
+ raise ImportError
128
+ except ImportError:
129
+ SwiGLU = SwiGLUFFN
130
+ XFORMERS_AVAILABLE = False
131
+
132
+ warnings.warn("xFormers is not available (SwiGLU)")
133
+
134
+
135
+ class SwiGLUFFNFused(SwiGLU):
136
+ """Fused SwiGLU Feed-Forward Network (FFN) layer.
137
+
138
+ Fused SwiGLU Feed-Forward Network (FFN) layer that uses xFormers' fused implementation if available.
139
+ This layer combines the linear transformations and activation into a single operation for improved performance.
140
+
141
+ Parameters
142
+ ----------
143
+ in_features : int
144
+ Input feature dimensionality (d).
145
+ hidden_features : int, optional
146
+ Hidden layer dimensionality (h). Defaults to in_features.
147
+ out_features : int, optional
148
+ Output feature dimensionality (d_out). Defaults to in_features.
149
+ act_layer : Callable[..., nn.Module], optional
150
+ Unused. Included for compatibility.
151
+ drop : float, optional
152
+ Dropout rate (unused).
153
+ bias : bool, optional
154
+ Whether to include bias terms in linear layers.
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ in_features: int,
160
+ hidden_features: Optional[int] = None,
161
+ out_features: Optional[int] = None,
162
+ act_layer: Callable[..., nn.Module] = None,
163
+ drop: float = 0.0,
164
+ bias: bool = True,
165
+ ) -> None:
166
+ """Inits :class:`SwiGLUFFNF
167
+
168
+ Parameters
169
+ ----------
170
+ in_features : int
171
+ Input feature dimensionality (d).
172
+ hidden_features : int, optional
173
+ Hidden layer dimensionality (h). Defaults to in_features.
174
+ out_features : int, optional
175
+ Output feature dimensionality (d_out). Defaults to in_features.
176
+ act_layer : Callable[..., nn.Module], optional
177
+ Unused. Included for compatibility.
178
+ drop : float, optional
179
+ Dropout rate (unused).
180
+ bias : bool, optional
181
+ Whether to include bias terms in linear layers.
182
+ """
183
+ out_features = out_features or in_features
184
+ hidden_features = hidden_features or in_features
185
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
186
+ super().__init__(
187
+ in_features=in_features,
188
+ hidden_features=hidden_features,
189
+ out_features=out_features,
190
+ bias=bias,
191
+ )
transformer_block.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+ import os
20
+ import warnings
21
+ from typing import Any, Callable, Dict, Optional, Tuple
22
+
23
+ import torch
24
+ from torch import nn
25
+
26
+ from .attention import Attention, MemEffAttention
27
+ from .drop_path import DropPath
28
+ from .layer_scale import LayerScale
29
+ from .mlp import Mlp
30
+
31
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
32
+ try:
33
+ if XFORMERS_ENABLED:
34
+ from xformers.ops import fmha, index_select_cat, scaled_index_add
35
+
36
+ XFORMERS_AVAILABLE = True
37
+ warnings.warn("xFormers is available (Block)")
38
+ else:
39
+ warnings.warn("xFormers is disabled (Block)")
40
+ raise ImportError
41
+ except ImportError:
42
+ XFORMERS_AVAILABLE = False
43
+
44
+ warnings.warn("xFormers is not available (Block)")
45
+
46
+
47
+ class Block(nn.Module):
48
+ """Transformer block with multi-head self-attention and MLP.
49
+
50
+ Parameters
51
+ ----------
52
+ dim : int
53
+ Dimension of the input features.
54
+ num_heads : int
55
+ Number of attention heads, by default 8.
56
+ mlp_ratio : float, optional
57
+ Ratio of the hidden dimension in the MLP to the input dimension, by default 4.0.
58
+ qkv_bias : bool, optional
59
+ Whether to add a bias to the query, key, and value projections, by default False.
60
+ proj_bias : bool, optional
61
+ Whether to add a bias to the output projection, by default True.
62
+ ffn_bias : bool, optional
63
+ Whether to add a bias to the MLP layers, by default True.
64
+ drop : float, optional
65
+ Dropout rate for the MLP layers, by default 0.0.
66
+ attn_drop : float, optional
67
+ Dropout rate for the attention weights, by default 0.0.
68
+ init_values : float or torch.Tensor, optional
69
+ Initial values for the layer scale, by default None. If a tensor is provided, it should have shape (dim,).
70
+ drop_path : float, optional
71
+ Drop path rate for stochastic depth, by default 0.0.
72
+ act_layer : Callable[..., nn.Module], optional
73
+ Activation layer for the MLP, by default nn.GELU.
74
+ norm_layer : Callable[..., nn.Module], optional
75
+ Normalization layer, by default nn.LayerNorm.
76
+ attn_class : Callable[..., nn.Module], optional
77
+ Attention class to use, by default Attention. Can be replaced with :class:`MemEffAttention` for memory-efficient
78
+ attention.
79
+ ffn_layer : Callable[..., nn.Module], optional
80
+ MLP class to use, by default Mlp.
81
+
82
+ Raises
83
+ ------
84
+ ValueError
85
+ If `dim` is not divisible by `num_heads`.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ dim: int,
91
+ num_heads: int,
92
+ mlp_ratio: float = 4.0,
93
+ qkv_bias: bool = False,
94
+ proj_bias: bool = True,
95
+ ffn_bias: bool = True,
96
+ drop: float = 0.0,
97
+ attn_drop: float = 0.0,
98
+ init_values=None,
99
+ drop_path: float = 0.0,
100
+ act_layer: Callable[..., nn.Module] = nn.GELU,
101
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
102
+ attn_class: Callable[..., nn.Module] = Attention,
103
+ ffn_layer: Callable[..., nn.Module] = Mlp,
104
+ ) -> None:
105
+ """Inits :class:`Block`.
106
+
107
+ Parameters
108
+ ----------
109
+ dim : int
110
+ Dimension of the input features.
111
+ num_heads : int
112
+ Number of attention heads, by default 8.
113
+ mlp_ratio : float, optional
114
+ Ratio of the hidden dimension in the MLP to the input dimension, by default 4.0.
115
+ qkv_bias : bool, optional
116
+ Whether to add a bias to the query, key, and value projections, by default False.
117
+ proj_bias : bool, optional
118
+ Whether to add a bias to the output projection, by default True.
119
+ ffn_bias : bool, optional
120
+ Whether to add a bias to the MLP layers, by default True.
121
+ drop : float, optional
122
+ Dropout rate for the MLP layers, by default 0.0.
123
+ attn_drop : float, optional
124
+ Dropout rate for the attention weights, by default 0.0.
125
+ init_values : float or torch.Tensor, optional
126
+ Initial values for the layer scale, by default None. If a tensor is provided, it should have shape (dim,).
127
+ drop_path : float, optional
128
+ Drop path rate for stochastic depth, by default 0.0.
129
+ act_layer : Callable[..., nn.Module], optional
130
+ Activation layer for the MLP, by default nn.GELU.
131
+ norm_layer : Callable[..., nn.Module], optional
132
+ Normalization layer, by default nn.LayerNorm.
133
+ attn_class : Callable[..., nn.Module], optional
134
+ Attention class to use, by default Attention. Can be replaced with :class:`MemEffAttention` for
135
+ memory-efficient attention.
136
+ ffn_layer : Callable[..., nn.Module], optional
137
+ MLP class to use, by default Mlp.
138
+
139
+ Raises
140
+ ------
141
+ ValueError
142
+ If `dim` is not divisible by `num_heads`.
143
+ """
144
+ super().__init__()
145
+ if dim % num_heads != 0:
146
+ raise ValueError(f"dim {dim} should be divisible by num_heads {num_heads}.")
147
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
148
+ self.norm1 = norm_layer(dim)
149
+ self.attn = attn_class(
150
+ dim,
151
+ num_heads=num_heads,
152
+ qkv_bias=qkv_bias,
153
+ proj_bias=proj_bias,
154
+ attn_drop=attn_drop,
155
+ proj_drop=drop,
156
+ )
157
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
158
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
159
+
160
+ self.norm2 = norm_layer(dim)
161
+ self.mlp = ffn_layer(
162
+ in_features=dim,
163
+ hidden_features=int(dim * mlp_ratio),
164
+ act_layer=act_layer,
165
+ drop=drop,
166
+ bias=ffn_bias,
167
+ )
168
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
169
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
170
+
171
+ self.sample_drop_ratio = drop_path
172
+
173
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
174
+ """Forward pass of :class:`Block`.
175
+
176
+ Parameters
177
+ ----------
178
+ x : torch.Tensor
179
+ Input tensor of shape (B, N, C) where B is the batch size, N is the sequence length, and C is
180
+ the feature dimension.
181
+
182
+ Returns
183
+ -------
184
+ torch.Tensor
185
+ Output tensor of shape (B, N, C) after applying the transformer block.
186
+ """
187
+
188
+ def attn_residual_func(x: torch.Tensor) -> torch.Tensor:
189
+ return self.ls1(self.attn(self.norm1(x)))
190
+
191
+ def ffn_residual_func(x: torch.Tensor) -> torch.Tensor:
192
+ return self.ls2(self.mlp(self.norm2(x)))
193
+
194
+ if self.training and self.sample_drop_ratio > 0.1:
195
+ # the overhead is compensated only for a drop path rate larger than 0.1
196
+ x = drop_add_residual_stochastic_depth(
197
+ x,
198
+ residual_func=attn_residual_func,
199
+ sample_drop_ratio=self.sample_drop_ratio,
200
+ )
201
+ x = drop_add_residual_stochastic_depth(
202
+ x,
203
+ residual_func=ffn_residual_func,
204
+ sample_drop_ratio=self.sample_drop_ratio,
205
+ )
206
+ elif self.training and self.sample_drop_ratio > 0.0:
207
+ x = x + self.drop_path1(attn_residual_func(x))
208
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
209
+ else:
210
+ x = x + attn_residual_func(x)
211
+ x = x + ffn_residual_func(x)
212
+ return x
213
+
214
+
215
+ def drop_add_residual_stochastic_depth(
216
+ x: torch.Tensor,
217
+ residual_func: Callable[[torch.Tensor], torch.Tensor],
218
+ sample_drop_ratio: float = 0.0,
219
+ ) -> torch.Tensor:
220
+ """Applies stochastic depth by dropping a subset of samples in the batch and adding a residual.
221
+
222
+ This function extracts a random subset of the batch, applies a residual function to it, and adds the result back
223
+ to the original tensor, scaling the residual appropriately.
224
+
225
+ Parameters
226
+ ----------
227
+ x : torch.Tensor
228
+ Input tensor of shape (B, N, D) where B is the batch size, N is the sequence length, and D is the
229
+ feature dimension.
230
+ residual_func : Callable[[torch.Tensor], torch.Tensor]
231
+ Function that takes a tensor of shape (B', N, D) and returns a tensor of the same shape, representing the
232
+ residual.
233
+ sample_drop_ratio : float, optional
234
+ Ratio of samples to drop from the batch, by default 0.0. If set to 0.0, no samples are dropped.
235
+
236
+ Returns
237
+ -------
238
+ torch.Tensor
239
+ Output tensor of the same shape as input x, with the residual added back to the original tensor.
240
+ """
241
+ # 1) extract subset using permutation
242
+ B = x.shape[0]
243
+ sample_subset_size = max(int(B * (1 - sample_drop_ratio)), 1)
244
+ brange = (torch.randperm(B, device=x.device))[:sample_subset_size]
245
+ x_subset = x[brange]
246
+
247
+ # 2) apply residual_func to get residual
248
+ residual = residual_func(x_subset)
249
+
250
+ x_flat = x.flatten(1)
251
+ residual = residual.flatten(1)
252
+
253
+ residual_scale_factor = B / sample_subset_size
254
+
255
+ # 3) add the residual
256
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
257
+ return x_plus_residual.view_as(x)
258
+
259
+
260
+ def get_branges_scales(x: torch.Tensor, sample_drop_ratio: float = 0.0) -> tuple[torch.Tensor, float]:
261
+ """Generates random indices for dropping samples in the batch and computes the scale factor for the residual.
262
+
263
+ This function extracts a random subset of the batch and computes a scale factor based on the original batch size
264
+ and the size of the subset. The scale factor is used to scale the residual when it is added back to the original
265
+ tensor.
266
+
267
+ Parameters
268
+ ----------
269
+ x : torch.Tensor
270
+ Input tensor of shape (B, N, D) where B is the batch size, N is the sequence length, and D is the
271
+ feature dimension.
272
+ sample_drop_ratio : float, optional
273
+ Ratio of samples to drop from the batch, by default 0.0. If set to 0.0, no samples are dropped.
274
+
275
+ Returns
276
+ -------
277
+ tuple[torch.Tensor, float]
278
+ A tuple containing:
279
+ - brange: A tensor of indices representing the subset of the batch to keep.
280
+ - residual_scale_factor: A float representing the scale factor for the residual.
281
+ """
282
+
283
+ B = x.shape[0]
284
+ sample_subset_size = max(int(B * (1 - sample_drop_ratio)), 1)
285
+ brange = (torch.randperm(B, device=x.device))[:sample_subset_size]
286
+ residual_scale_factor = B / sample_subset_size
287
+ return brange, residual_scale_factor
288
+
289
+
290
+ def add_residual(
291
+ x: torch.Tensor,
292
+ brange: torch.Tensor,
293
+ residual: torch.Tensor,
294
+ residual_scale_factor: float,
295
+ scaling_vector: Optional[torch.Tensor] = None,
296
+ ) -> torch.Tensor:
297
+ """Adds a residual to the input tensor, scaling it appropriately.
298
+
299
+ This function takes a tensor `x`, a set of indices `brange`, and a residual tensor, and adds the residual to the
300
+ corresponding indices in `x`. If a scaling vector is provided, it scales the residual before adding it.
301
+
302
+ Parameters
303
+ ----------
304
+ x : torch.Tensor
305
+ Input tensor of shape (B, N, D) where B is the batch size, N is the sequence length, and D is the
306
+ feature dimension.
307
+ brange : torch.Tensor
308
+ torch.Tensor of indices representing the subset of the batch to which the residual will be added.
309
+ residual : torch.Tensor
310
+ Residual tensor of shape (B', N, D) where B' is the size of the subset defined by `brange`.
311
+ residual_scale_factor : float
312
+ Scale factor for the residual, computed as the ratio of the original batch size to the subset size.
313
+ scaling_vector : Optional[torch.Tensor], optional
314
+ Scaling vector to scale the residual before adding it, by default None. If provided, it should have shape (D,).
315
+
316
+ Returns
317
+ -------
318
+ torch.Tensor
319
+ Output tensor of the same shape as input `x`, with the residual added back to the original tensor.
320
+ """
321
+ if scaling_vector is None:
322
+ x_flat = x.flatten(1)
323
+ residual = residual.flatten(1)
324
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
325
+ else:
326
+ x_plus_residual = scaled_index_add(
327
+ x,
328
+ brange,
329
+ residual.to(dtype=x.dtype),
330
+ scaling=scaling_vector,
331
+ alpha=residual_scale_factor,
332
+ )
333
+ return x_plus_residual
334
+
335
+
336
+ attn_bias_cache: Dict[Tuple, Any] = {}
337
+
338
+
339
+ def get_attn_bias_and_cat(
340
+ x_list: list[torch.Tensor], branges: Optional[list[torch.Tensor]] = None
341
+ ) -> tuple[Any, torch.Tensor]:
342
+ """Get attention bias and concatenate tensors from a list of tensors.
343
+
344
+ This function checks if the attention bias for the given shapes is already cached. If not, it creates a new
345
+ attention bias using the `fmha.BlockDiagonalMask` from xFormers. It then concatenates the tensors in `x_list`
346
+ based on the provided `branges`. If `branges` is not provided, it concatenates the tensors directly.
347
+
348
+ Parameters
349
+ ----------
350
+ x_list : list of torch.Tensors
351
+ List of tensors to concatenate. Each tensor should have shape (B, N, D) where B is the batch size, N is the
352
+ sequence length, and D is the feature dimension.
353
+ branges : list of torch.Tensors, optional
354
+ List of tensors containing indices for selecting samples from the batch. If provided, it will index select
355
+ and concatenate the tensors in `x_list`. If not provided, it will concatenate the tensors directly.
356
+
357
+ Returns
358
+ -------
359
+ tuple[Any, torch.Tensor]
360
+ A tuple containing:
361
+ - attn_bias: Attention bias tensor created using `fmha.BlockDiagonalMask` from xFormers.
362
+ - cat_tensors: Concatenated tensor of shape (1, B', D) where B' is the total number of samples selected from
363
+ the batch based on `branges` or the total number of samples in `x_list` if `branges` is not provided.
364
+ If `branges` is provided, the concatenated tensor will have shape (1, sum of sizes in branges, D).
365
+ If `branges` is not provided, the concatenated tensor will have shape (1, sum of batch sizes in x_list, D).
366
+ """
367
+
368
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
369
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
370
+ if all_shapes not in attn_bias_cache.keys():
371
+ seqlens = []
372
+ for b, x in zip(batch_sizes, x_list):
373
+ for _ in range(b):
374
+ seqlens.append(x.shape[1])
375
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
376
+ attn_bias._batch_sizes = batch_sizes
377
+ attn_bias_cache[all_shapes] = attn_bias
378
+
379
+ if branges is not None:
380
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
381
+ else:
382
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
383
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
384
+
385
+ return attn_bias_cache[all_shapes], cat_tensors
386
+
387
+
388
+ def drop_add_residual_stochastic_depth_list(
389
+ x_list: list[torch.Tensor],
390
+ residual_func: Callable[[torch.Tensor, Any], torch.Tensor],
391
+ sample_drop_ratio: float = 0.0,
392
+ scaling_vector=None,
393
+ ) -> list[torch.Tensor]:
394
+ """Applies stochastic depth to a list of tensors, dropping a subset of samples in each tensor and adding a residual.
395
+ This function processes a list of tensors, generating random indices for dropping samples in each tensor,
396
+ computing the attention bias, and applying a residual function to each tensor. The results are then combined
397
+ and returned as a list of tensors.
398
+
399
+ Parameters
400
+ ----------
401
+ x_list : list of torch.Tensors
402
+ List of tensors to process. Each tensor should have shape (B, N, D) where B is the batch size, N is the sequence
403
+ length, and D is the feature dimension.
404
+ residual_func : Callable[[torch.Tensor, Any], torch.Tensor]
405
+ Function that takes a tensor of shape (B', N, D) and an attention bias (if applicable) and returns a tensor of
406
+ the same shape, representing the residual.
407
+ sample_drop_ratio : float, optional
408
+ Ratio of samples to drop from the batch, by default 0.0. If set to 0.0, no samples are dropped.
409
+ scaling_vector : Optional[torch.Tensor], optional
410
+ Scaling vector to scale the residual before adding it, by default None. If provided, it should have shape (D,).
411
+
412
+ Returns
413
+ -------
414
+ list of torch.Tensors
415
+ List of output tensors, each of the same shape as the corresponding input tensor in `x_list`, with the residual
416
+ added back to the original tensor.
417
+ """
418
+ # 1) generate random set of indices for dropping samples in the batch
419
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
420
+ branges = [s[0] for s in branges_scales]
421
+ residual_scale_factors = [s[1] for s in branges_scales]
422
+
423
+ # 2) get attention bias and index+concat the tensors
424
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
425
+
426
+ # 3) apply residual_func to get residual, and split the result
427
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
428
+
429
+ outputs = []
430
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
431
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
432
+ return outputs
433
+
434
+
435
+ class NestedTensorBlock(Block):
436
+ """Transformer block with multi-head self-attention and MLP, supporting nested tensors.
437
+
438
+ This class extends the :class:`Block` class to support nested tensors, allowing for more flexible input shapes.
439
+
440
+ Parameters
441
+ ----------
442
+ dim : int
443
+ Dimension of the input features.
444
+ num_heads : int
445
+ Number of attention heads, by default 8.
446
+ mlp_ratio : float, optional
447
+ Ratio of the hidden dimension in the MLP to the input dimension, by default 4.0.
448
+ qkv_bias : bool, optional
449
+ Whether to add a bias to the query, key, and value projections, by default False.
450
+ proj_bias : bool, optional
451
+ Whether to add a bias to the output projection, by default True.
452
+ ffn_bias : bool, optional
453
+ Whether to add a bias to the feed-forward network, by default True.
454
+ drop : float, optional
455
+ Dropout rate for the MLP layers, by default 0.0.
456
+ attn_drop : float, optional
457
+ Dropout rate for the attention weights, by default 0.0.
458
+ init_values : float or torch.Tensor, optional
459
+ Initial values for the layer scale, by default None. If a tensor is provided, it should have shape (dim,).
460
+ drop_path : float, optional
461
+ Drop path rate for stochastic depth, by default 0.0.
462
+ act_layer : Callable[..., nn.Module], optional
463
+ Activation layer for the MLP, by default nn.GELU.
464
+ norm_layer : Callable[..., nn.Module], optional
465
+ Normalization layer, by default nn.LayerNorm.
466
+ attn_class : Callable[..., nn.Module], optional
467
+ Attention class to use, by default Attention. Can be replaced with :class:`MemEffAttention` for
468
+ memory-efficient attention.
469
+ ffn_layer : Callable[..., nn.Module], optional
470
+ MLP class to use, by default :class:`Mlp`.
471
+ sample_drop_ratio : float, optional
472
+ Drop path rate for stochastic depth, by default 0.0. This is used to control the stochastic depth
473
+ during training.
474
+ """
475
+
476
+ def forward_nested(self, x_list: list[torch.Tensor]) -> list[torch.Tensor]:
477
+ """Forward pass for list of tensors, applying attention and MLP with stochastic depth.
478
+
479
+ This method applies the attention and MLP layers to a list of tensors, applying stochastic depth if the model is
480
+ in training mode and `sample_drop_ratio` is greater than 0.0. It uses the :class:`MemEffAttention` class
481
+ for memory-efficient attention. The method expects `x_list` to be a list of tensors, where each tensor has
482
+ the same feature dimension. If the model is not in training mode or `sample_drop_ratio` is 0.0,
483
+ it applies the attention and MLP layers without stochastic depth.
484
+
485
+ Parameters
486
+ ----------
487
+ x_list : list[torch.Tensor]
488
+ List of tensors to process. Each tensor should have shape (B, N, D) where B is the batch size, N is the
489
+ sequence length, and D is the feature dimension.
490
+
491
+ Returns
492
+ -------
493
+ list[torch.Tensor]
494
+ List of processed tensors, each with the same shape as the corresponding input tensor in `x_list`.
495
+ """
496
+ assert isinstance(self.attn, MemEffAttention)
497
+
498
+ if self.training and self.sample_drop_ratio > 0.0:
499
+
500
+ def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
501
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
502
+
503
+ def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
504
+ return self.mlp(self.norm2(x))
505
+
506
+ x_list = drop_add_residual_stochastic_depth_list(
507
+ x_list,
508
+ residual_func=attn_residual_func,
509
+ sample_drop_ratio=self.sample_drop_ratio,
510
+ scaling_vector=(self.ls1.gamma if isinstance(self.ls1, LayerScale) else None),
511
+ )
512
+ x_list = drop_add_residual_stochastic_depth_list(
513
+ x_list,
514
+ residual_func=ffn_residual_func,
515
+ sample_drop_ratio=self.sample_drop_ratio,
516
+ scaling_vector=(self.ls2.gamma if isinstance(self.ls1, LayerScale) else None),
517
+ )
518
+ return x_list
519
+ else:
520
+
521
+ def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
522
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
523
+
524
+ def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
525
+ return self.ls2(self.mlp(self.norm2(x)))
526
+
527
+ attn_bias, x = get_attn_bias_and_cat(x_list)
528
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
529
+ x = x + ffn_residual_func(x)
530
+ return attn_bias.split(x)
531
+
532
+ def forward(self, x_or_x_list: torch.Tensor | list[torch.Tensor]) -> torch.Tensor | list[torch.Tensor]:
533
+ """Forward pass of :class:`NestedTensorBlock`.
534
+
535
+ Parameters
536
+ ----------
537
+ x_or_x_list : torch.Tensor or list[torch.Tensor]
538
+ Input tensor or list of tensors. If a tensor is provided, it should have shape (B, N, D) where B is the
539
+ batch size, N is the sequence length, and D is the feature dimension. If a list of tensors is provided,
540
+ each tensor should have the same shape.
541
+
542
+ Returns
543
+ -------
544
+ torch.Tensor or list[torch.Tensor]
545
+ Output tensor or list of tensors after applying the transformer block. If a tensor is provided, the output
546
+ will be a tensor of the same shape. If a list of tensors is provided, the output will be a list of tensors,
547
+ each with the same shape as the corresponding input tensor.
548
+
549
+ Raises
550
+ ------
551
+ AssertionError
552
+ If `xFormers` is not available.
553
+ ValueError
554
+ If `x_or_x_list` is neither a torch.Tensor nor a list of torch.Tensors.
555
+ """
556
+ if isinstance(x_or_x_list, torch.Tensor):
557
+ return super().forward(x_or_x_list)
558
+ elif isinstance(x_or_x_list, list):
559
+ if not XFORMERS_AVAILABLE:
560
+ raise AssertionError("xFormers is required for using nested tensors")
561
+ return self.forward_nested(x_or_x_list)
562
+ else:
563
+ raise ValueError(
564
+ f"Expected input to be a torch.Tensor or a list of torch.Tensors, got {type(x_or_x_list)}."
565
+ )
vision_transformer.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+
20
+ from functools import partial
21
+ from typing import Callable
22
+ from typing_extensions import override
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from .attention import MemEffAttention
28
+ from .transformer_block import NestedTensorBlock as Block
29
+ from .vision_transformer_base import (
30
+ DinoVisionTransformerBase,
31
+ DinoVisionTransformerDim,
32
+ DinoVisionTransformerFFNLayer,
33
+ )
34
+
35
+
36
+ class DinoVisionTransformer(DinoVisionTransformerBase):
37
+ """DinoVisionTransformer for 2D images.
38
+
39
+ Parameters
40
+ ----------
41
+ img_size : int or tuple[int, int]
42
+ Input image size, either a single integer or a tuple of two integers (height, width).
43
+ patch_size : int or tuple[int, int]
44
+ Patch size, either a single integer or a tuple of two integers (height, width).
45
+ in_chans : int
46
+ Number of input channels, default is 3.
47
+ embed_dim : int
48
+ Embedding dimension.
49
+ depth : int
50
+ Depth of transformer.
51
+ num_heads : int
52
+ Number of attention heads.
53
+ mlp_ratio : int
54
+ Ratio of mlp hidden dim to embedding dim.
55
+ qkv_bias : bool
56
+ Enable bias for qkv if True.
57
+ proj_bias : bool
58
+ Enable bias for proj in attn if True.
59
+ ffn_bias : bool
60
+ Enable bias for ffn if True.
61
+ drop_path_rate : float
62
+ Stochastic depth rate.
63
+ drop_path_uniform : bool
64
+ Apply uniform drop rate across blocks.
65
+ weight_init : str
66
+ Weight init scheme.
67
+ init_values : float
68
+ Layer-scale init values.
69
+ act_layer : nn.Module
70
+ MLP activation layer.
71
+ block_fn : nn.Module
72
+ Transformer block class.
73
+ ffn_layer : DinoVisionTransformerFFNLayer
74
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
75
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
76
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
77
+ block_chunks : int
78
+ Split block sequence into block_chunks units for FSDP wrap.
79
+ num_register_tokens : int
80
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
81
+ interpolate_antialias : str
82
+ Flag to apply anti-aliasing when interpolating positional embeddings.
83
+ interpolate_offset : float
84
+ Work-around offset to apply when interpolating positional embeddings.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ img_size: int | tuple[int, int] = 224,
90
+ patch_size: int | tuple[int, int] = 16,
91
+ in_chans: int = 3,
92
+ embed_dim: int = 768,
93
+ depth: int = 12,
94
+ num_heads: int = 12,
95
+ mlp_ratio: float = 4.0,
96
+ qkv_bias: bool = True,
97
+ ffn_bias: bool = True,
98
+ proj_bias: bool = True,
99
+ drop_path_rate: float = 0.0,
100
+ drop_path_uniform: bool = False,
101
+ init_values: float | None = None, # for layerscale: None or 0 => no layerscale
102
+ act_layer: Callable[..., nn.Module] = nn.GELU,
103
+ block_fn: Callable[..., Block] = Block,
104
+ ffn_layer: DinoVisionTransformerFFNLayer = DinoVisionTransformerFFNLayer.MLP,
105
+ block_chunks: int = 1,
106
+ num_register_tokens: int = 0,
107
+ interpolate_antialias: bool = False,
108
+ interpolate_offset: float = 0.1,
109
+ ) -> None:
110
+ """Inits :class:`DinoVisionTransformer`.
111
+
112
+ Parameters
113
+ ----------
114
+ img_size : int or tuple[int, int]
115
+ Input image size, either a single integer or a tuple of two integers (height, width).
116
+ patch_size : int or tuple[int, int]
117
+ Patch size, either a single integer or a tuple of two integers (height, width).
118
+ in_chans : int
119
+ Number of input channels, default is 3.
120
+ embed_dim : int
121
+ Embedding dimension.
122
+ depth : int
123
+ Depth of transformer.
124
+ num_heads : int
125
+ Number of attention heads.
126
+ mlp_ratio : int
127
+ Ratio of mlp hidden dim to embedding dim.
128
+ qkv_bias : bool
129
+ Enable bias for qkv if True.
130
+ proj_bias : bool
131
+ Enable bias for proj in attn if True.
132
+ ffn_bias : bool
133
+ Enable bias for ffn if True.
134
+ drop_path_rate : float
135
+ Stochastic depth rate.
136
+ drop_path_uniform : bool
137
+ Apply uniform drop rate across blocks.
138
+ weight_init : str
139
+ Weight init scheme.
140
+ init_values : float
141
+ Layer-scale init values.
142
+ act_layer : nn.Module
143
+ MLP activation layer.
144
+ block_fn : nn.Module
145
+ Transformer block class.
146
+ ffn_layer : DinoVisionTransformerFFNLayer
147
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
148
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
149
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
150
+ block_chunks : int
151
+ Split block sequence into block_chunks units for FSDP wrap.
152
+ num_register_tokens : int
153
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
154
+ interpolate_antialias : str
155
+ Flag to apply anti-aliasing when interpolating positional embeddings.
156
+ interpolate_offset : float
157
+ Work-around offset to apply when interpolating positional embeddings.
158
+ """
159
+ super().__init__(
160
+ dim=DinoVisionTransformerDim.TWO_D,
161
+ img_size=img_size,
162
+ patch_size=patch_size,
163
+ in_chans=in_chans,
164
+ embed_dim=embed_dim,
165
+ depth=depth,
166
+ num_heads=num_heads,
167
+ mlp_ratio=mlp_ratio,
168
+ qkv_bias=qkv_bias,
169
+ ffn_bias=ffn_bias,
170
+ proj_bias=proj_bias,
171
+ drop_path_rate=drop_path_rate,
172
+ drop_path_uniform=drop_path_uniform,
173
+ init_values=init_values,
174
+ act_layer=act_layer,
175
+ block_fn=block_fn,
176
+ ffn_layer=ffn_layer,
177
+ block_chunks=block_chunks,
178
+ num_register_tokens=num_register_tokens,
179
+ interpolate_antialias=interpolate_antialias,
180
+ interpolate_offset=interpolate_offset,
181
+ )
182
+
183
+ @override
184
+ def _interpolate_and_reshape_pos_embed(
185
+ self, patch_pos_embed: torch.Tensor, patches_resolution: tuple[int, int], dim: int, interpolation_kwargs: dict
186
+ ) -> torch.Tensor:
187
+ """Interpolate and reshape 2D patch positional embeddings.
188
+
189
+ Parameters
190
+ ----------
191
+ patch_pos_embed : torch.Tensor
192
+ Positional embedding tensor of shape (1, N, C).
193
+ patches_resolution : tuple of ints
194
+ Number of patches along each spatial dimension.
195
+ dim : int
196
+ Embedding dimension.
197
+ interpolation_kwargs : dict
198
+ Arguments passed to `F.interpolate`.
199
+
200
+ Returns
201
+ -------
202
+ torch.Tensor
203
+ Reshaped and interpolated tensor of shape (1, H, W, C),
204
+ where H, W are the number of patches along height and width.
205
+ """
206
+ patch_pos_embed = patch_pos_embed.reshape(1, *patches_resolution, dim).permute(0, 3, 1, 2)
207
+ patch_pos_embed = nn.functional.interpolate(
208
+ patch_pos_embed,
209
+ mode="bicubic",
210
+ antialias=self.interpolate_antialias,
211
+ **interpolation_kwargs,
212
+ )
213
+ return patch_pos_embed.permute(0, 2, 3, 1)
214
+
215
+
216
+ def vit_small(
217
+ patch_size: int | tuple[int, int] = 16,
218
+ num_register_tokens: int = 0,
219
+ **kwargs,
220
+ ) -> DinoVisionTransformer:
221
+ """Builds a small 2d vision transformer with 384-dimensional embeddings, 12 layers, 6 heads, and 4x MLP ratio.
222
+
223
+ Parameters
224
+ ----------
225
+ patch_size : int or tuple[int, int]
226
+ Patch size, either a single integer or a tuple of two integers (height, width). Default is 16.
227
+ num_register_tokens : int
228
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
229
+ kwargs : dict
230
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer` constructor.
231
+
232
+ Returns
233
+ -------
234
+ DinoVisionTransformer
235
+ A small 2d vision transformer.
236
+ """
237
+ model = DinoVisionTransformer(
238
+ patch_size=patch_size,
239
+ embed_dim=384,
240
+ depth=12,
241
+ num_heads=6,
242
+ mlp_ratio=4,
243
+ block_fn=partial(Block, attn_class=MemEffAttention),
244
+ num_register_tokens=num_register_tokens,
245
+ **kwargs,
246
+ )
247
+ return model
248
+
249
+
250
+ def vit_base(
251
+ patch_size: int | tuple[int, int] = 16,
252
+ num_register_tokens: int = 0,
253
+ **kwargs,
254
+ ) -> DinoVisionTransformer:
255
+ """Builds a base 2d vision transformer with 768-dimensional embeddings, 12 layers, 12 heads, and 4x MLP ratio.
256
+
257
+ Parameters
258
+ ----------
259
+ patch_size : int or tuple[int, int]
260
+ Patch size, either a single integer or a tuple of two integers (height, width). Default is 16.
261
+ num_register_tokens : int
262
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
263
+ kwargs : dict
264
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer` constructor.
265
+
266
+ Returns
267
+ -------
268
+ DinoVisionTransformer
269
+ A base 2d vision transformer.
270
+ """
271
+ model = DinoVisionTransformer(
272
+ patch_size=patch_size,
273
+ embed_dim=768,
274
+ depth=12,
275
+ num_heads=12,
276
+ mlp_ratio=4,
277
+ block_fn=partial(Block, attn_class=MemEffAttention),
278
+ num_register_tokens=num_register_tokens,
279
+ **kwargs,
280
+ )
281
+ return model
282
+
283
+
284
+ def vit_large(
285
+ patch_size: int | tuple[int, int] = 16,
286
+ num_register_tokens: int = 0,
287
+ **kwargs,
288
+ ) -> DinoVisionTransformer:
289
+ """Builds a large 2d vision transformer with 1024-dimensional embeddings, 24 layers, 16 heads, and 4x MLP ratio.
290
+
291
+ Parameters
292
+ ----------
293
+ patch_size : int or tuple[int, int]
294
+ Patch size, either a single integer or a tuple of two integers (height, width). Default is 16.
295
+ num_register_tokens : int
296
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
297
+ kwargs : dict
298
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer` constructor.
299
+
300
+ Returns
301
+ -------
302
+ DinoVisionTransformer
303
+ A large 2d vision transformer.
304
+ """
305
+ model = DinoVisionTransformer(
306
+ patch_size=patch_size,
307
+ embed_dim=1024,
308
+ depth=24,
309
+ num_heads=16,
310
+ mlp_ratio=4,
311
+ block_fn=partial(Block, attn_class=MemEffAttention),
312
+ num_register_tokens=num_register_tokens,
313
+ **kwargs,
314
+ )
315
+ return model
316
+
317
+
318
+ def vit_giant2(
319
+ patch_size: int | tuple[int, int] = 16,
320
+ num_register_tokens: int = 0,
321
+ **kwargs,
322
+ ) -> DinoVisionTransformer:
323
+ """Builds a giant2 vision transformer with 1536-dimensional embeddings, 40 layers, 24 heads, and 4x MLP ratio.
324
+
325
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
326
+
327
+ Parameters
328
+ ----------
329
+ patch_size : int or tuple[int, int]
330
+ Patch size, either a single integer or a tuple of two integers (height, width). Default is 16.
331
+ num_register_tokens : int
332
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
333
+ kwargs : dict
334
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer` constructor.
335
+
336
+ Returns
337
+ -------
338
+ DinoVisionTransformer
339
+ A giant2 vision transformer.
340
+ """
341
+ model = DinoVisionTransformer(
342
+ patch_size=patch_size,
343
+ embed_dim=1536,
344
+ depth=40,
345
+ num_heads=24,
346
+ mlp_ratio=4,
347
+ block_fn=partial(Block, attn_class=MemEffAttention),
348
+ num_register_tokens=num_register_tokens,
349
+ **kwargs,
350
+ )
351
+ return model
vision_transformer_3d.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # References:
17
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
18
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
19
+
20
+ from functools import partial
21
+ from typing import Callable
22
+ from typing_extensions import override
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from .attention import MemEffAttention
28
+ from .transformer_block import NestedTensorBlock as Block
29
+ from .vision_transformer_base import (
30
+ DinoVisionTransformerBase,
31
+ DinoVisionTransformerDim,
32
+ DinoVisionTransformerFFNLayer,
33
+ )
34
+
35
+
36
+ class DinoVisionTransformer3d(DinoVisionTransformerBase):
37
+ """DinoVisionTransformer for 3D images.
38
+
39
+ Parameters
40
+ ----------
41
+ img_size : int or tuple[int, int, int]
42
+ Input image size, either a single integer or a tuple of three integers (depth, height, width).
43
+ patch_size : int or tuple[int, int, int]
44
+ Patch size, either a single integer or a tuple of three integers (depth, height, width).
45
+ in_chans : int
46
+ Number of input channels, default is 3.
47
+ embed_dim : int
48
+ Embedding dimension.
49
+ depth : int
50
+ Depth of transformer.
51
+ num_heads : int
52
+ Number of attention heads.
53
+ mlp_ratio : int
54
+ Ratio of mlp hidden dim to embedding dim.
55
+ qkv_bias : bool
56
+ Enable bias for qkv if True.
57
+ proj_bias : bool
58
+ Enable bias for proj in attn if True.
59
+ ffn_bias : bool
60
+ Enable bias for ffn if True.
61
+ drop_path_rate : float
62
+ Stochastic depth rate.
63
+ drop_path_uniform : bool
64
+ Apply uniform drop rate across blocks.
65
+ weight_init : str
66
+ Weight init scheme.
67
+ init_values : float
68
+ Layer-scale init values.
69
+ act_layer : nn.Module
70
+ MLP activation layer.
71
+ block_fn : nn.Module
72
+ Transformer block class.
73
+ ffn_layer : DinoVisionTransformerFFNLayer
74
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
75
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
76
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
77
+ block_chunks : int
78
+ Split block sequence into block_chunks units for FSDP wrap.
79
+ num_register_tokens : int
80
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
81
+ interpolate_antialias : str
82
+ Flag to apply anti-aliasing when interpolating positional embeddings.
83
+ interpolate_offset : float
84
+ Work-around offset to apply when interpolating positional embeddings.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ img_size: int | tuple[int, int, int] = 224,
90
+ patch_size: int | tuple[int, int, int] = 16,
91
+ in_chans: int = 3,
92
+ embed_dim: int = 768,
93
+ depth: int = 12,
94
+ num_heads: int = 12,
95
+ mlp_ratio: float = 4.0,
96
+ qkv_bias: bool = True,
97
+ ffn_bias: bool = True,
98
+ proj_bias: bool = True,
99
+ drop_path_rate: float = 0.0,
100
+ drop_path_uniform: bool = False,
101
+ init_values: float | None = None, # for layerscale: None or 0 => no layerscale
102
+ act_layer: Callable[..., nn.Module] = nn.GELU,
103
+ block_fn: Callable[..., nn.Module] = Block,
104
+ ffn_layer: DinoVisionTransformerFFNLayer = DinoVisionTransformerFFNLayer.MLP,
105
+ block_chunks: int = 1,
106
+ num_register_tokens: int = 0,
107
+ interpolate_antialias: bool = False,
108
+ interpolate_offset: float = 0.1,
109
+ ) -> None:
110
+ """Inits :class:`DinoVisionTransformer3d`.
111
+
112
+ Parameters
113
+ ----------
114
+ img_size : int or tuple[int, int, int]
115
+ Input image size, either a single integer or a tuple of three integers (depth, height, width).
116
+ patch_size : int or tuple[int, int, int]
117
+ Patch size, either a single integer or a tuple of three integers (depth, height, width).
118
+ in_chans : int
119
+ Number of input channels, default is 3.
120
+ embed_dim : int
121
+ Embedding dimension.
122
+ depth : int
123
+ Depth of transformer.
124
+ num_heads : int
125
+ Number of attention heads.
126
+ mlp_ratio : int
127
+ Ratio of mlp hidden dim to embedding dim.
128
+ qkv_bias : bool
129
+ Enable bias for qkv if True.
130
+ proj_bias : bool
131
+ Enable bias for proj in attn if True.
132
+ ffn_bias : bool
133
+ Enable bias for ffn if True.
134
+ drop_path_rate : float
135
+ Stochastic depth rate.
136
+ drop_path_uniform : bool
137
+ Apply uniform drop rate across blocks.
138
+ weight_init : str
139
+ Weight init scheme.
140
+ init_values : float
141
+ Layer-scale init values.
142
+ act_layer : nn.Module
143
+ MLP activation layer.
144
+ block_fn : nn.Module
145
+ Transformer block class.
146
+ ffn_layer : DinoVisionTransformerFFNLayer
147
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
148
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
149
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
150
+ block_chunks : int
151
+ Split block sequence into block_chunks units for FSDP wrap.
152
+ num_register_tokens : int
153
+ Number of extra cls tokens (so-called "registers").
154
+ interpolate_antialias : str
155
+ Flag to apply anti-aliasing when interpolating positional embeddings.
156
+ interpolate_offset : float
157
+ Work-around offset to apply when interpolating positional embeddings.
158
+ """
159
+ super().__init__(
160
+ dim=DinoVisionTransformerDim.THREE_D,
161
+ img_size=img_size,
162
+ patch_size=patch_size,
163
+ in_chans=in_chans,
164
+ embed_dim=embed_dim,
165
+ depth=depth,
166
+ num_heads=num_heads,
167
+ mlp_ratio=mlp_ratio,
168
+ qkv_bias=qkv_bias,
169
+ ffn_bias=ffn_bias,
170
+ proj_bias=proj_bias,
171
+ drop_path_rate=drop_path_rate,
172
+ drop_path_uniform=drop_path_uniform,
173
+ init_values=init_values,
174
+ act_layer=act_layer,
175
+ block_fn=block_fn,
176
+ ffn_layer=ffn_layer,
177
+ block_chunks=block_chunks,
178
+ num_register_tokens=num_register_tokens,
179
+ interpolate_antialias=interpolate_antialias,
180
+ interpolate_offset=interpolate_offset,
181
+ )
182
+
183
+ @override
184
+ def _interpolate_and_reshape_pos_embed(
185
+ self,
186
+ patch_pos_embed: torch.Tensor,
187
+ patches_resolution: tuple[int, int, int],
188
+ dim: int,
189
+ interpolation_kwargs: dict,
190
+ ) -> torch.Tensor:
191
+ """Interpolate and reshape 3D patch positional embeddings.
192
+
193
+ Parameters
194
+ ----------
195
+ patch_pos_embed : torch.Tensor
196
+ Positional embedding tensor of shape (1, N, C).
197
+ patches_resolution : tuple of ints
198
+ Number of patches along each spatial dimension.
199
+ dim : int
200
+ Embedding dimension.
201
+ interpolation_kwargs : dict
202
+ Arguments passed to `F.interpolate`.
203
+
204
+ Returns
205
+ -------
206
+ torch.Tensor
207
+ Reshaped and interpolated tensor of shape (1, D, H, W, C),
208
+ where D, H, W are the number of patches along depth, height, and width.
209
+ """
210
+ patch_pos_embed = patch_pos_embed.reshape(1, *patches_resolution, dim).permute(0, 4, 1, 2, 3)
211
+ patch_pos_embed = nn.functional.interpolate(
212
+ patch_pos_embed,
213
+ mode="trilinear",
214
+ antialias=self.interpolate_antialias,
215
+ **interpolation_kwargs,
216
+ )
217
+ return patch_pos_embed.permute(0, 2, 3, 4, 1)
218
+
219
+
220
+ def vit_3d_small(
221
+ patch_size: int | tuple[int, int, int] = (16, 16, 16),
222
+ num_register_tokens: int = 4,
223
+ **kwargs,
224
+ ) -> DinoVisionTransformer3d:
225
+ """Builds a small 3d vision transformer with 384-dimensional embeddings, 12 layers, 6 heads, and 4x MLP ratio.
226
+
227
+ Parameters
228
+ ----------
229
+ patch_size : int or tuple[int, int, int]
230
+ Patch size, either a single integer or a tuple of three integers (depth, height, width).
231
+ Default is (16, 16, 16).
232
+ num_register_tokens : int
233
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 4.
234
+ kwargs : dict
235
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer3d` constructor.
236
+
237
+ Returns
238
+ -------
239
+ DinoVisionTransformer3d
240
+ A small 3d vision transformer.
241
+ """
242
+ model = DinoVisionTransformer3d(
243
+ patch_size=patch_size,
244
+ embed_dim=384,
245
+ depth=12,
246
+ num_heads=6,
247
+ mlp_ratio=4,
248
+ block_fn=partial(Block, attn_class=MemEffAttention),
249
+ num_register_tokens=num_register_tokens,
250
+ **kwargs,
251
+ )
252
+ return model
253
+
254
+
255
+ def vit_3d_base(
256
+ patch_size: int | tuple[int, int, int] = (16, 16, 16),
257
+ num_register_tokens: int = 4,
258
+ **kwargs,
259
+ ) -> DinoVisionTransformer3d:
260
+ """Builds a base 3d vision transformer with 768-dimensional embeddings, 12 layers, 12 heads, and 4x MLP ratio.
261
+
262
+ Parameters
263
+ ----------
264
+ patch_size : int or tuple[int, int, int]
265
+ Patch size, either a single integer or a tuple of three integers (depth, height, width).
266
+ Default is (16, 16, 16).
267
+ num_register_tokens : int
268
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 4.
269
+ kwargs : dict
270
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer3d` constructor.
271
+
272
+ Returns
273
+ -------
274
+ DinoVisionTransformer3d
275
+ A base 3d vision transformer.
276
+ """
277
+ model = DinoVisionTransformer3d(
278
+ patch_size=patch_size,
279
+ embed_dim=768,
280
+ depth=12,
281
+ num_heads=12,
282
+ mlp_ratio=4,
283
+ block_fn=partial(Block, attn_class=MemEffAttention),
284
+ num_register_tokens=num_register_tokens,
285
+ **kwargs,
286
+ )
287
+ return model
288
+
289
+
290
+ def vit_3d_large(
291
+ patch_size: int | tuple[int, int, int] = (16, 16, 16),
292
+ num_register_tokens: int = 4,
293
+ **kwargs,
294
+ ) -> DinoVisionTransformer3d:
295
+ """Builds a large 3d vision transformer with 1024-dimensional embeddings, 24 layers, 16 heads, and 4x MLP ratio.
296
+
297
+ Parameters
298
+ ----------
299
+ patch_size : int or tuple[int, int, int]
300
+ Patch size, either a single integer or a tuple of three integers (depth, height, width).
301
+ Default is (16, 16, 16).
302
+ num_register_tokens : int
303
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 4.
304
+ kwargs : dict
305
+ Additional keyword arguments to pass to the :class:`DinoVisionTransformer3d` constructor.
306
+
307
+ Returns
308
+ -------
309
+ DinoVisionTransformer3d
310
+ A large 3d vision transformer.
311
+ """
312
+ model = DinoVisionTransformer3d(
313
+ patch_size=patch_size,
314
+ embed_dim=1024,
315
+ depth=24,
316
+ num_heads=16,
317
+ mlp_ratio=4,
318
+ block_fn=partial(Block, attn_class=MemEffAttention),
319
+ num_register_tokens=num_register_tokens,
320
+ **kwargs,
321
+ )
322
+ return model
vision_transformer_base.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 AI for Oncology Research Group. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # References:
16
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
17
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
18
+
19
+ from abc import abstractmethod
20
+ from enum import Enum
21
+ import logging
22
+ import math
23
+ from functools import partial
24
+ from typing import Callable, Sequence
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.utils.checkpoint
29
+ from torch.nn.init import trunc_normal_
30
+
31
+ from .mlp import Mlp
32
+ from .transformer_block import NestedTensorBlock as Block
33
+ from .patch_embed import PatchEmbed, PatchEmbed3d
34
+ from .swiglu_ffn import SwiGLUFFNFused
35
+ from .helpers import make_2tuple, make_3tuple
36
+
37
+ logger = logging.getLogger("dinov2")
38
+
39
+
40
+ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
41
+ if not depth_first and include_root:
42
+ fn(module=module, name=name)
43
+ for child_name, child_module in module.named_children():
44
+ child_name = ".".join((name, child_name)) if name else child_name
45
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
46
+ if depth_first and include_root:
47
+ fn(module=module, name=name)
48
+ return module
49
+
50
+
51
+ class BlockChunk(nn.ModuleList):
52
+ """Block chunk for FSDP wrap."""
53
+
54
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
55
+ """Forward pass through the block chunk.
56
+
57
+ Parameters
58
+ ----------
59
+ x : torch.Tensor
60
+ Input tensor.
61
+
62
+ Returns
63
+ -------
64
+ torch.Tensor
65
+ Output tensor.
66
+ """
67
+ for b in self:
68
+ x = b(x)
69
+ return x
70
+
71
+
72
+ class DinoVisionTransformerDim(str, Enum):
73
+ """Dimension type for DinoVisionTransformer."""
74
+
75
+ TWO_D = "2d"
76
+ THREE_D = "3d"
77
+
78
+
79
+ class DinoVisionTransformerFFNLayer(str, Enum):
80
+ """FFN layer type for DinoVisionTransformer."""
81
+
82
+ MLP = "mlp"
83
+ SWIGLU = "swiglu"
84
+ SWIGLU_FUSED = "swiglufused"
85
+ IDENTITY = "identity"
86
+
87
+ @classmethod
88
+ def _missing_(cls, value):
89
+ if isinstance(value, str):
90
+ value = value.lower()
91
+ for member in cls:
92
+ if member.value == value:
93
+ return member
94
+ raise ValueError(f"{value!r} is not a valid {cls.__name__}")
95
+
96
+
97
+ class DinoVisionTransformerBase(nn.Module):
98
+ """Base class for DinoVisionTransformer, supporting both 2D and 3D vision transformers.
99
+
100
+ Parameters
101
+ ----------
102
+ dim : DinoVisionTransformerDim
103
+ Dimension type, either DinoVisionTransformerDim.TWO_D or DinoVisionTransformerDim.THREE_D.
104
+ img_size : int, tuple[int, int] or tuple[int, int, int]
105
+ Input image size, either a single integer or a tuple.
106
+ For 2D, it should be a tuple of two integers (height, width).
107
+ For 3D, it should be a tuple of three integers (depth, height, width).
108
+ patch_size : int, tuple[int, int] or tuple[int, int, int]
109
+ Patch size, either a single integer or a tuple.
110
+ For 2D, it should be a tuple of two integers (height, width).
111
+ For 3D, it should be a tuple of three integers (depth, height, width).
112
+ in_chans : int
113
+ Number of input channels, default is 3.
114
+ embed_dim : int
115
+ Embedding dimension.
116
+ depth : int
117
+ Depth of transformer.
118
+ num_heads : int
119
+ Number of attention heads.
120
+ mlp_ratio : int
121
+ Ratio of mlp hidden dim to embedding dim.
122
+ qkv_bias : bool
123
+ Enable bias for qkv if True.
124
+ proj_bias : bool
125
+ Enable bias for proj in attn if True.
126
+ ffn_bias : bool
127
+ Enable bias for ffn if True.
128
+ drop_path_rate : float
129
+ Stochastic depth rate.
130
+ drop_path_uniform : bool
131
+ Apply uniform drop rate across blocks.
132
+ weight_init : str
133
+ Weight init scheme.
134
+ init_values : float
135
+ Layer-scale init values.
136
+ act_layer : nn.Module
137
+ MLP activation layer.
138
+ block_fn : nn.Module
139
+ Transformer block class.
140
+ ffn_layer : DinoVisionTransformerFFNLayer
141
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
142
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
143
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
144
+ block_chunks : int
145
+ Split block sequence into block_chunks units for FSDP wrap.
146
+ num_register_tokens : int
147
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
148
+ interpolate_antialias : str
149
+ Flag to apply anti-aliasing when interpolating positional embeddings.
150
+ interpolate_offset : float
151
+ Work-around offset to apply when interpolating positional embeddings.
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ dim: DinoVisionTransformerDim,
157
+ img_size: int | tuple[int, int] | tuple[int, int, int] = 224,
158
+ patch_size: int | tuple[int, int] | tuple[int, int, int] = 16,
159
+ in_chans: int = 3,
160
+ embed_dim: int = 768,
161
+ depth: int = 12,
162
+ num_heads: int = 12,
163
+ mlp_ratio: float = 4.0,
164
+ qkv_bias: bool = True,
165
+ ffn_bias: bool = True,
166
+ proj_bias: bool = True,
167
+ drop_path_rate: float = 0.0,
168
+ drop_path_uniform: bool = False,
169
+ init_values: float | None = None, # for layerscale: None or 0 => no layerscale
170
+ act_layer: Callable[..., nn.Module] = nn.GELU,
171
+ block_fn: Callable[..., nn.Module] = Block,
172
+ ffn_layer: DinoVisionTransformerFFNLayer = DinoVisionTransformerFFNLayer.MLP,
173
+ block_chunks: int = 1,
174
+ num_register_tokens: int = 0,
175
+ interpolate_antialias: bool = False,
176
+ interpolate_offset: float = 0.1,
177
+ ) -> None:
178
+ """Inits :class:`DinoVisionTransformerBase`.
179
+
180
+ Parameters
181
+ ----------
182
+ dim : DinoVisionTransformerDim
183
+ Dimension type, either DinoVisionTransformerDim.TWO_D or DinoVisionTransformerDim.THREE_D.
184
+ img_size : int, tuple[int, int] or tuple[int, int, int]
185
+ Input image size, either a single integer or a tuple.
186
+ For 2D, it should be a tuple of two integers (height, width).
187
+ For 3D, it should be a tuple of three integers (depth, height, width).
188
+ patch_size : int, tuple[int, int] or tuple[int, int, int]
189
+ Patch size, either a single integer or a tuple.
190
+ For 2D, it should be a tuple of two integers (height, width).
191
+ For 3D, it should be a tuple of three integers (depth, height, width).
192
+ in_chans : int
193
+ Number of input channels, default is 3.
194
+ embed_dim : int
195
+ Embedding dimension.
196
+ depth : int
197
+ Depth of transformer.
198
+ num_heads : int
199
+ Number of attention heads.
200
+ mlp_ratio : int
201
+ Ratio of mlp hidden dim to embedding dim.
202
+ qkv_bias : bool
203
+ Enable bias for qkv if True.
204
+ proj_bias : bool
205
+ Enable bias for proj in attn if True.
206
+ ffn_bias : bool
207
+ Enable bias for ffn if True.
208
+ drop_path_rate : float
209
+ Stochastic depth rate.
210
+ drop_path_uniform : bool
211
+ Apply uniform drop rate across blocks.
212
+ weight_init : str
213
+ Weight init scheme.
214
+ init_values : float
215
+ Layer-scale init values.
216
+ act_layer : nn.Module
217
+ MLP activation layer.
218
+ block_fn : nn.Module
219
+ Transformer block class.
220
+ ffn_layer : DinoVisionTransformerFFNLayer
221
+ Type of FFN layer to use, can be DinoVisionTransformerFFNLayer.MLP,
222
+ DinoVisionTransformerFFNLayer.SWIGLU, DinoVisionTransformerFFNLayer.SWIGLU_FUSED,
223
+ or DinoVisionTransformerFFNLayer.IDENTITY. Default is DinoVisionTransformerFFNLayer.MLP.
224
+ block_chunks : int
225
+ Split block sequence into block_chunks units for FSDP wrap.
226
+ num_register_tokens : int
227
+ Number of extra tokens for the model to deposit information (so-called "registers"). Default is 0.
228
+ interpolate_antialias : str
229
+ Flag to apply anti-aliasing when interpolating positional embeddings.
230
+ interpolate_offset : float
231
+ Work-around offset to apply when interpolating positional embeddings.
232
+ """
233
+
234
+ super().__init__()
235
+ self.logger = logging.getLogger(type(self).__name__)
236
+ self.dim = dim
237
+
238
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
239
+
240
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
241
+ self.num_tokens = 1
242
+ self.n_blocks = depth
243
+ self.num_heads = num_heads
244
+
245
+ self.patch_size = make_2tuple(patch_size) if dim == DinoVisionTransformerDim.TWO_D else make_3tuple(patch_size)
246
+ self.img_size = make_2tuple(img_size) if dim == DinoVisionTransformerDim.TWO_D else make_3tuple(img_size)
247
+
248
+ if len(self.patch_size) != len(self.img_size):
249
+ raise ValueError("Patch size and image size must have the same number of dimensions")
250
+
251
+ self.num_register_tokens = num_register_tokens
252
+ self.interpolate_antialias = interpolate_antialias
253
+ self.interpolate_offset = interpolate_offset
254
+
255
+ self.patch_embed = (PatchEmbed if dim == DinoVisionTransformerDim.TWO_D else PatchEmbed3d)(
256
+ img_size=self.img_size,
257
+ patch_size=self.patch_size,
258
+ in_chans=in_chans,
259
+ embed_dim=embed_dim,
260
+ )
261
+ num_patches = self.patch_embed.num_patches
262
+
263
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
264
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
265
+ assert num_register_tokens >= 0
266
+ self.register_tokens = (
267
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
268
+ )
269
+
270
+ if drop_path_uniform is True:
271
+ dpr = [drop_path_rate] * depth
272
+ else:
273
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
274
+
275
+ if ffn_layer == DinoVisionTransformerFFNLayer.MLP:
276
+ self.logger.info("Using MLP layer as FFN")
277
+ ffn_layer = Mlp
278
+ elif (
279
+ ffn_layer == DinoVisionTransformerFFNLayer.SWIGLU or ffn_layer == DinoVisionTransformerFFNLayer.SWIGLU_FUSED
280
+ ):
281
+ self.logger.info("Using SwiGLU layer as FFN")
282
+ ffn_layer = SwiGLUFFNFused
283
+ else: # ffn_layer == DinoVisionTransformerFFNLayer.IDENTITY:
284
+ self.logger.info("Using Identity layer as FFN")
285
+ ffn_layer = nn.Identity
286
+
287
+ blocks_list = [
288
+ block_fn(
289
+ dim=embed_dim,
290
+ num_heads=num_heads,
291
+ mlp_ratio=mlp_ratio,
292
+ qkv_bias=qkv_bias,
293
+ proj_bias=proj_bias,
294
+ ffn_bias=ffn_bias,
295
+ drop_path=dpr[i],
296
+ norm_layer=norm_layer,
297
+ act_layer=act_layer,
298
+ ffn_layer=ffn_layer,
299
+ init_values=init_values,
300
+ )
301
+ for i in range(depth)
302
+ ]
303
+ if block_chunks > 0:
304
+ self.chunked_blocks = True
305
+ chunked_blocks = []
306
+ chunksize = depth // block_chunks
307
+ for i in range(0, depth, chunksize):
308
+ # this is to keep the block index consistent if we chunk the block list
309
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
310
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
311
+ else:
312
+ self.chunked_blocks = False
313
+ self.blocks = nn.ModuleList(blocks_list)
314
+
315
+ self.norm = norm_layer(embed_dim)
316
+ self.head = nn.Identity()
317
+
318
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
319
+
320
+ self.init_weights()
321
+
322
+ def init_weights(self) -> None:
323
+ """Initialize weights of the model."""
324
+ trunc_normal_(self.pos_embed, std=0.02)
325
+ nn.init.normal_(self.cls_token, std=1e-6)
326
+ if self.register_tokens is not None:
327
+ nn.init.normal_(self.register_tokens, std=1e-6)
328
+ named_apply(init_weights_vit_timm, self)
329
+
330
+ def _interpolate_pos_encoding(
331
+ self, x: torch.Tensor, img_shape: tuple[int, int] | tuple[int, int, int]
332
+ ) -> torch.Tensor:
333
+ """Interpolate the positional encoding to match the input image shape.
334
+
335
+ This method resizes the positional encoding tensor to match the spatial dimensions of the input tensor.
336
+
337
+ Parameters
338
+ ----------
339
+ x : torch.Tensor
340
+ Input tensor of shape (B, N, C) where B is the batch size, N is the number of patches + tokens,
341
+ and C is the embedding dimension.
342
+ img_shape : tuple[int, int] | tuple[int, int, int]
343
+ Spatial dimensions of the input image. For 2D, it should be a tuple of two integers (height, width).
344
+ For 3D, it should be a tuple of three integers (depth, height, width).
345
+
346
+ Returns
347
+ -------
348
+ torch.Tensor
349
+ Interpolated positional encoding tensor of shape (1, N, C), where N is the number of patches + tokens
350
+ """
351
+ previous_dtype = x.dtype
352
+ num_image_patches = x.shape[1] - 1
353
+
354
+ N = self.pos_embed.shape[1] - 1
355
+
356
+ if num_image_patches == N and all(img_shape[i] == img_shape[i + 1] for i in range(len(img_shape) - 1)):
357
+ return self.pos_embed
358
+
359
+ pos_embed = self.pos_embed.float()
360
+
361
+ class_pos_embed = pos_embed[:, 0]
362
+ patch_pos_embed = pos_embed[:, 1:]
363
+ dim = x.shape[-1]
364
+
365
+ img_shape0 = [img_shape[i] // self.patch_size[i] for i in range(len(img_shape))]
366
+
367
+ patches_resolution = self.patch_embed.patches_resolution # Recover the number of patches in each dimension
368
+
369
+ if N != math.prod(patches_resolution):
370
+ raise ValueError(
371
+ f"Mismatch: learned pos_embed has {N} tokens, but expected {math.prod(patches_resolution)} patches "
372
+ f"corresponding to {patches_resolution} resolution."
373
+ )
374
+
375
+ interpolation_kwargs = {}
376
+ if self.interpolate_offset:
377
+ scale_factor = [float(s + self.interpolate_offset) / m for (s, m) in zip(img_shape0, patches_resolution)]
378
+ interpolation_kwargs["scale_factor"] = scale_factor
379
+ else:
380
+ # Simply specify an output size instead of a scale factor
381
+ interpolation_kwargs["size"] = img_shape0
382
+
383
+ patch_pos_embed = self._interpolate_and_reshape_pos_embed(
384
+ patch_pos_embed, patches_resolution, dim, interpolation_kwargs
385
+ )
386
+
387
+ if tuple(img_shape0) != patch_pos_embed.shape[1:-1]:
388
+ raise ValueError(
389
+ f"Positional embedding shape mismatch: expected {img_shape0}, got {patch_pos_embed.shape[1:-1]}. "
390
+ "This may lead to unexpected behavior."
391
+ )
392
+
393
+ patch_pos_embed = patch_pos_embed.view(1, -1, dim)
394
+
395
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
396
+
397
+ @abstractmethod
398
+ def _interpolate_and_reshape_pos_embed(
399
+ self, patch_pos_embed: torch.Tensor, patches_resolution: tuple[int, ...], dim: int, interpolation_kwargs: dict
400
+ ) -> torch.Tensor:
401
+ """Subclasses should implement interpolation and reshaping appropriate for 2D or 3D positional embeddings.
402
+
403
+ Parameters
404
+ ----------
405
+ patch_pos_embed : torch.Tensor
406
+ Positional embedding tensor of shape (1, N, C).
407
+ patches_resolution : tuple of ints
408
+ Number of patches along each spatial dimension.
409
+ dim : int
410
+ Embedding dimension.
411
+ interpolation_kwargs : dict
412
+ Arguments passed to `F.interpolate`.
413
+
414
+ Returns
415
+ -------
416
+ torch.Tensor
417
+ Reshaped and interpolated tensor of shape (1, ..., ..., C).
418
+ """
419
+ raise NotImplementedError("Subclasses must implement `_interpolate_and_reshape_pos_embed` method.")
420
+
421
+ def _prepare_tokens_with_masks(self, x: torch.Tensor, masks: torch.Tensor | None = None) -> torch.Tensor:
422
+ """Prepare tokens with masks for the input tensor.
423
+
424
+ This method applies patch embedding, adds class tokens, and interpolates positional encodings.
425
+ If masks are provided, it replaces the corresponding patches with a mask token.
426
+
427
+ Parameters
428
+ ----------
429
+ x : torch.Tensor
430
+ Input tensor of shape (B, C, H, W) for 2D or (B, C, D, H, W) for 3D,
431
+ where B is the batch size, C is the number of channels, and H, W (or D, H, W) are the spatial dimensions.
432
+ masks : torch.Tensor, optional
433
+ Optional mask tensor of shape (B, N) where B is the batch size and N is the number of patches.
434
+ Default is None.
435
+
436
+ Returns
437
+ -------
438
+ torch.Tensor
439
+ Prepared tensor of shape (B, N, C) where B is the batch size, N is the number of patches + tokens,
440
+ and C is the embedding dimension.
441
+ """
442
+ x_shape = x.shape[2:]
443
+ x = self.patch_embed(x)
444
+ if masks is not None:
445
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
446
+
447
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
448
+ x = x + self._interpolate_pos_encoding(x, x_shape)
449
+ if self.register_tokens is not None:
450
+ x = torch.cat(
451
+ (
452
+ x[:, :1],
453
+ self.register_tokens.expand(x.shape[0], -1, -1),
454
+ x[:, 1:],
455
+ ),
456
+ dim=1,
457
+ )
458
+
459
+ return x
460
+
461
+ def forward_features_list(
462
+ self, x_list: list[torch.Tensor], masks_list: list[torch.Tensor]
463
+ ) -> list[dict[str, torch.Tensor]]:
464
+ """Forward pass for a list of input tensors with corresponding masks.
465
+
466
+ Parameters
467
+ ----------
468
+ x_list : list[torch.Tensor]
469
+ List of input tensors, each of shape (B, C, H, W) for 2D or (B, C, D, H, W) for 3D,
470
+ where B is the batch size, C is the number of channels, and H, W (or D, H, W) are the spatial dimensions.
471
+ masks_list : list[torch.Tensor]
472
+ List of mask tensors, each of shape (B, N) where B is the batch size and N is the number of patches.
473
+
474
+ Returns
475
+ -------
476
+ list[dict[str, torch.Tensor]]
477
+ List of dictionaries containing the normalized outputs and masks for each input tensor.
478
+ """
479
+ x = [self._prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
480
+ for blk in self.blocks:
481
+ x = blk(x)
482
+
483
+ all_x = x
484
+ output = []
485
+ for x, masks in zip(all_x, masks_list):
486
+ x_norm = self.norm(x)
487
+ output.append(
488
+ {
489
+ "x_norm_clstoken": x_norm[:, 0],
490
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
491
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
492
+ "x_prenorm": x,
493
+ "masks": masks,
494
+ }
495
+ )
496
+ return output
497
+
498
+ def forward_features(
499
+ self,
500
+ x: torch.Tensor | list[torch.Tensor],
501
+ masks: torch.Tensor | list[torch.Tensor] = None,
502
+ ) -> dict[str, torch.Tensor]:
503
+ """Return features from the input.
504
+
505
+ Parameters
506
+ ----------
507
+ x : torch.Tensor | list[torch.Tensor]
508
+ Input tensor or list of input tensors.
509
+ masks : torch.Tensor | list[torch.Tensor], optional
510
+ Mask tensor or list of mask tensors.
511
+
512
+ Returns
513
+ -------
514
+ dict[str, torch.Tensor]
515
+ Dictionary containing the normalized outputs and masks.
516
+ """
517
+ if isinstance(x, list):
518
+ return self.forward_features_list(x, masks)
519
+
520
+ x = self._prepare_tokens_with_masks(x, masks)
521
+
522
+ for blk in self.blocks:
523
+ x = blk(x)
524
+
525
+ x_norm = self.norm(x)
526
+ return {
527
+ "x_norm_clstoken": x_norm[:, 0],
528
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
529
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
530
+ "x_prenorm": x,
531
+ "masks": masks,
532
+ }
533
+
534
+ def _get_intermediate_layers_not_chunked(self, x: torch.Tensor, n: int | list[int] = 1) -> list[torch.Tensor]:
535
+ """Get intermediate layers from the transformer blocks."""
536
+ x = self._prepare_tokens_with_masks(x)
537
+ # If n is an int, take the n last blocks. If it's a list, take them
538
+ output, total_block_len = [], len(self.blocks)
539
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
540
+ for i, blk in enumerate(self.blocks):
541
+ x = blk(x)
542
+ if i in blocks_to_take:
543
+ output.append(x)
544
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
545
+ return output
546
+
547
+ def _get_intermediate_layers_chunked(self, x: torch.Tensor, n: int | list[int] = 1) -> list[torch.Tensor]:
548
+ """Get intermediate layers from the transformer blocks when using chunked blocks."""
549
+ x = self._prepare_tokens_with_masks(x)
550
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
551
+ # If n is an int, take the n last blocks. If it's a list, take them
552
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
553
+ for block_chunk in self.blocks:
554
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
555
+ x = blk(x)
556
+ if i in blocks_to_take:
557
+ output.append(x)
558
+ i += 1
559
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
560
+ return output
561
+
562
+ def get_intermediate_layers(
563
+ self,
564
+ x: torch.Tensor,
565
+ n: int | Sequence = 1, # Layers or n last layers to take
566
+ reshape: bool = False,
567
+ return_class_token: bool = False,
568
+ norm: bool = True,
569
+ ) -> tuple[torch.Tensor | tuple[torch.Tensor]]:
570
+ """Get intermediate layers from the transformer blocks.
571
+
572
+ Parameters
573
+ ----------
574
+ x : torch.Tensor
575
+ Input tensor.
576
+ n : int or Sequence, optional
577
+ Number of layers or specific layers to take.
578
+ reshape : bool, optional
579
+ Whether to reshape the output.
580
+ return_class_token : bool, optional
581
+ Whether to return the class token.
582
+ norm : bool, optional
583
+ Whether to apply normalization.
584
+
585
+ Returns
586
+ -------
587
+ tuple[torch.Tensor | tuple[torch.Tensor]]
588
+ Intermediate layers from the transformer blocks.
589
+ """
590
+ if self.chunked_blocks:
591
+ outputs = self._get_intermediate_layers_chunked(x, n)
592
+ else:
593
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
594
+
595
+ if norm:
596
+ outputs = [self.norm(out) for out in outputs]
597
+
598
+ class_tokens = [out[:, 0] for out in outputs]
599
+ outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs]
600
+
601
+ if reshape:
602
+ B = x.size(0)
603
+ spatial_dims = x.shape[2:]
604
+ outputs = [
605
+ out.reshape([B] + [s // p for s, p in zip(spatial_dims, self.patch_size)] + [-1])
606
+ .permute([0] + [x.ndim - 1] + list(range(1, x.ndim - 1)))
607
+ .contiguous()
608
+ for out in outputs
609
+ ]
610
+
611
+ if return_class_token:
612
+ return tuple(zip(outputs, class_tokens))
613
+
614
+ return tuple(outputs)
615
+
616
+ def forward(self, *args, is_training=False, **kwargs) -> dict[str, torch.Tensor] | torch.Tensor:
617
+ """Forward pass of :class:`DinoVisionTransformerBase`."""
618
+ ret = self.forward_features(*args, **kwargs)
619
+ if is_training:
620
+ return ret
621
+ else:
622
+ return self.head(ret["x_norm_clstoken"])
623
+
624
+
625
+ def init_weights_vit_timm(module: nn.Module, name: str = "") -> None:
626
+ """ViT weight initialization, original timm impl (for reproducibility)"""
627
+ if isinstance(module, nn.Linear):
628
+ trunc_normal_(module.weight, std=0.02)
629
+ if module.bias is not None:
630
+ nn.init.zeros_(module.bias)