Model
ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4
- Task:Image Text To Text
- Libraries:transformerspytorch
- Formats:safetensors
- Languages:GermanEnglishSpanishFrenchItalianJapanese
- License:other
Dedicated endpoint
Sign in to deployInference Providers
This hub serves this model on demand.
Try itSpaces
Create a Space with this modelUse this model
Choose individual files there, or download a full snapshot with the Python example below.
Download with the whiteduck client
pip install https://provyd.xyz/clients/whiteduck-0.1.0-py3-none-any.whl
wd login --host 'https://api.provyd.xyz'
wd download 'ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Using the Hugging Face client instead
Install huggingface_hub with pip install huggingface_hub, then download this pinned snapshot. Set HF_TOKEN (the variable the Hugging Face client reads) to a whiteduck Read token for private repositories. Running the downloaded model requires software that supports its architecture.
Keep your whiteduck token away from calls that ignore HF_ENDPOINT, such as list_inference_endpoints: they send it to Hugging Face. See Docs.
from huggingface_hub import snapshot_download
import os
path = snapshot_download(
repo_id='ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4',
revision='f145a010eb6cafac2e532b8b81c2dc76df47ff25',
endpoint='https://api.provyd.xyz',
token=os.environ.get("HF_TOKEN") or False,
)Load with transformers
import os
os.environ["HF_ENDPOINT"] = 'https://api.provyd.xyz'
from transformers import AutoModel, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4')
model = AutoModel.from_pretrained('ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4')Use with local apps
This hub is self-hosted, so each command points the tool at it. Add a whiteduck access token as HF_TOKEN (the variable the Hugging Face client reads) for private repositories.
vLLM
# vLLM downloads through huggingface_hub, which honours HF_ENDPOINT; set HF_TOKEN for a private repository.
HF_ENDPOINT='https://api.provyd.xyz' vllm serve 'ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Clone with git
git clone 'https://api.provyd.xyz/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Clone with git over SSH
git clone 'ssh://git@wd.provyd.xyz:2222/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Needs an SSH key on your account. Add an SSH key
Use the API
Read repository metadata at this commit. Set HF_TOKEN (the variable the Hugging Face client reads) to a whiteduck Read token. Tokens grant account-level access, not access to just this model.
curl 'https://api.provyd.xyz/api/models/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4/revision/f145a010eb6cafac2e532b8b81c2dc76df47ff25' \
-H "Authorization: Bearer $HF_TOKEN"Inference is separate from file storage. The owner must configure and start a supported model using the inference controls. To call it you need a model API key (made on the model page), or a token of any scope (Read or stronger) from the model owner. Visitors can use the try box only when the owner allows it. A token cannot enable unavailable GPU hardware.
Blame for modeling_radio.py at cb6f83b
| Line | Commit | Author | Date | Code |
|---|---|---|---|---|
| 1 | Add files using upload-large-folder toolcb6f83b | ankit | # π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨ | |
| 2 | # This file was automatically generated from src/transformers/models/radio/modular_radio.py. | |||
| 3 | # Do NOT edit this file manually as any edits will be overwritten by the generation of | |||
| 4 | # the file from the modular. If any change should be done, please apply the change to the | |||
| 5 | # modular_radio.py file directly. One of our CI enforces this. | |||
| 6 | # π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨ | |||
| 7 | # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | |||
| 8 | # | |||
| 9 | # Licensed under the Apache License, Version 2.0 (the "License"); | |||
| 10 | # you may not use this file except in compliance with the License. | |||
| 11 | # You may obtain a copy of the License at | |||
| 12 | # | |||
| 13 | # http://www.apache.org/licenses/LICENSE-2.0 | |||
| 14 | # | |||
| 15 | # Unless required by applicable law or agreed to in writing, software | |||
| 16 | # distributed under the License is distributed on an "AS IS" BASIS, | |||
| 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |||
| 18 | # See the License for the specific language governing permissions and | |||
| 19 | # limitations under the License. | |||
| 20 | ||||
| 21 | from collections.abc import Callable | |||
| 22 | from dataclasses import dataclass | |||
| 23 | ||||
| 24 | import torch | |||
| 25 | import torch.nn.functional as F | |||
| 26 | from torch import nn | |||
| 27 | from transformers import initialization as init | |||
| 28 | from transformers.activations import ACT2FN | |||
| 29 | from transformers.modeling_layers import GradientCheckpointingLayer | |||
| 30 | from transformers.modeling_outputs import BaseModelOutput, ModelOutput | |||
| 31 | from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel | |||
| 32 | from transformers.processing_utils import Unpack | |||
| 33 | from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple | |||
| 34 | from transformers.utils.generic import merge_with_config_defaults | |||
| 35 | from transformers.utils.output_capturing import capture_outputs | |||
| 36 | ||||
| 37 | from transformers.conversion_mapping import register_checkpoint_conversion_mapping | |||
| 38 | from transformers.core_model_loading import Chunk, WeightConverter, WeightRenaming | |||
| 39 | ||||
| 40 | from .configuration_radio import RadioConfig | |||
| 41 | ||||
| 42 | ||||
| 43 | def register_radio_conversion_mapping(): | |||
| 44 | """ | |||
| 45 | Register the conversion mapping for RADIO vision models. | |||
| 46 | ||||
| 47 | Note: This is done here instead of in the global `conversion_mapping.py` because Transformers | |||
| 48 | 5.8 predates the radio architecture and therefore ships no mapping for it. The language model | |||
| 49 | needs no equivalent: `nemotron_h` has been upstream since v5.3.0, including its conversion | |||
| 50 | mapping. The mapping rewrites released C-RADIO checkpoints (timm-style | |||
| 51 | `radio_model.model.blocks` with fused qkv) into this implementation's module tree. | |||
| 52 | """ | |||
| 53 | ||||
| 54 | register_checkpoint_conversion_mapping( | |||
| 55 | "radio", | |||
| 56 | [ | |||
| 57 | WeightRenaming("radio_model.model.patch_generator.video_embedder", "embeddings.video_patch_projection"), | |||
| 58 | WeightRenaming("radio_model.model.patch_generator.embedder", "embeddings.patch_projection"), | |||
| 59 | WeightRenaming("radio_model.model.patch_generator.pos_embed", "embeddings.position_embedding"), | |||
| 60 | WeightRenaming("radio_model.model.patch_generator.cls_token.token", "embeddings.cls_register_token"), | |||
| 61 | WeightRenaming("radio_model.model.blocks", "encoder.layer"), | |||
| 62 | WeightRenaming("attn.proj", "attention.output.dense"), | |||
| 63 | WeightRenaming("radio_model.input_conditioner", "input_conditioner"), | |||
| 64 | WeightRenaming("radio_model.summary_idxs", "summary_idxs"), | |||
| 65 | WeightConverter( | |||
| 66 | source_patterns="attn.qkv", | |||
| 67 | target_patterns=[ | |||
| 68 | "attention.attention.query", | |||
| 69 | "attention.attention.key", | |||
| 70 | "attention.attention.value", | |||
| 71 | ], | |||
| 72 | operations=[Chunk(dim=0)], | |||
| 73 | ), | |||
| 74 | ], | |||
| 75 | overwrite=True, | |||
| 76 | ) | |||
| 77 | ||||
| 78 | ||||
| 79 | @dataclass | |||
| 80 | class RadioModelOutput(ModelOutput): | |||
| 81 | """Output of [`RadioModel`]. | |||
| 82 | ||||
| 83 | Args: | |||
| 84 | summary (`torch.FloatTensor` of shape `(batch_size, num_summary_idxs * hidden_size)`): | |||
| 85 | Flattened summary embedding, gathered from the cls tokens selected by `config.summary_idxs`. | |||
| 86 | features (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`): | |||
| 87 | Dense spatial patch features. | |||
| 88 | last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): | |||
| 89 | Full token sequence (prefix tokens + patches) from the final encoder layer. | |||
| 90 | hidden_states (`tuple[torch.FloatTensor]`, *optional*, returned when `output_hidden_states=True`): | |||
| 91 | Tuple of `(batch_size, sequence_length, hidden_size)` tensors, one for the embedding output plus one for | |||
| 92 | each encoder layer. | |||
| 93 | attentions (`tuple[torch.FloatTensor]`, *optional*, returned when `output_attentions=True`): | |||
| 94 | Tuple of `(batch_size, num_heads, sequence_length, sequence_length)` attention weights, one per layer. | |||
| 95 | """ | |||
| 96 | ||||
| 97 | summary: torch.FloatTensor | None = None | |||
| 98 | features: torch.FloatTensor | None = None | |||
| 99 | last_hidden_state: torch.FloatTensor | None = None | |||
| 100 | hidden_states: tuple[torch.FloatTensor] | None = None | |||
| 101 | attentions: tuple[torch.FloatTensor] | None = None | |||
| 102 | ||||
| 103 | ||||
| 104 | class RadioInputConditioner(nn.Module): | |||
| 105 | """Normalizes pixel values; arithmetic is done in float32 then cast back.""" | |||
| 106 | ||||
| 107 | def __init__(self, config: RadioConfig): | |||
| 108 | super().__init__() | |||
| 109 | self.register_buffer("norm_mean", torch.tensor(config.norm_mean).view(-1, 1, 1), persistent=True) | |||
| 110 | self.register_buffer("norm_std", torch.tensor(config.norm_std).view(-1, 1, 1), persistent=True) | |||
| 111 | ||||
| 112 | def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: | |||
| 113 | normalized = (pixel_values.float() - self.norm_mean.float()) / self.norm_std.float() | |||
| 114 | return normalized.to(pixel_values.dtype) | |||
| 115 | ||||
| 116 | ||||
| 117 | class RadioPatchEmbeddings(nn.Module): | |||
| 118 | """Cropped Position Embedding (CPE) patch generator. | |||
| 119 | ||||
| 120 | Splits the image into patches, projects them, adds a resolution-interpolated | |||
| 121 | absolute position embedding, and prepends learned cls + register tokens. | |||
| 122 | """ | |||
| 123 | ||||
| 124 | def __init__(self, config: RadioConfig): | |||
| 125 | super().__init__() | |||
| 126 | self.patch_size = config.patch_size | |||
| 127 | self.embed_dim = config.hidden_size | |||
| 128 | self.num_cls_tokens = config.num_cls_tokens | |||
| 129 | self.num_registers = config.num_registers | |||
| 130 | ||||
| 131 | self.max_rows = config.max_img_size // config.patch_size | |||
| 132 | self.max_cols = config.max_img_size // config.patch_size | |||
| 133 | num_positions = self.max_rows * self.max_cols | |||
| 134 | ||||
| 135 | self.patch_projection = nn.Linear(config.num_channels * config.patch_size**2, config.hidden_size, bias=False) | |||
| 136 | if config.video_temporal_patch_size is not None: | |||
| 137 | self.video_patch_projection = nn.Linear( | |||
| 138 | config.video_temporal_patch_size * config.num_channels * config.patch_size**2, | |||
| 139 | config.hidden_size, | |||
| 140 | bias=False, | |||
| 141 | ) | |||
| 142 | self.position_embedding = nn.Parameter(torch.zeros(1, num_positions, config.hidden_size)) | |||
| 143 | self.cls_register_token = nn.Parameter( | |||
| 144 | torch.zeros(config.num_cls_tokens + config.num_registers, config.hidden_size) | |||
| 145 | ) | |||
| 146 | ||||
| 147 | def _image_to_patches(self, pixel_values: torch.Tensor) -> torch.Tensor: | |||
| 148 | ps = self.patch_size | |||
| 149 | batch, channels, height, width = pixel_values.shape | |||
| 150 | rows, cols = height // ps, width // ps | |||
| 151 | patches = pixel_values.reshape(batch, channels, rows, ps, cols, ps) | |||
| 152 | patches = patches.permute(0, 2, 4, 1, 3, 5).reshape(batch, rows * cols, channels * ps * ps) | |||
| 153 | return patches | |||
| 154 | ||||
| 155 | def _interpolate_position_embedding(self, input_dims: tuple[int, int], dtype: torch.dtype) -> torch.Tensor: | |||
| 156 | pos = self.position_embedding.reshape(1, self.max_rows, self.max_cols, -1).permute(0, 3, 1, 2) | |||
| 157 | max_dim = max(input_dims) | |||
| 158 | pos = F.interpolate(pos.float(), size=(max_dim, max_dim), mode="bilinear", align_corners=False).to(dtype) | |||
| 159 | if input_dims[0] < pos.shape[-2]: | |||
| 160 | pos = pos[..., : input_dims[0], :] | |||
| 161 | if input_dims[1] < pos.shape[-1]: | |||
| 162 | pos = pos[..., :, : input_dims[1]] | |||
| 163 | if pos.shape[-2:] != tuple(input_dims): | |||
| 164 | pos = F.interpolate(pos.float(), size=tuple(input_dims), mode="bilinear", align_corners=False).to(dtype) | |||
| 165 | return pos.flatten(2).permute(0, 2, 1) | |||
| 166 | ||||
| 167 | def forward(self, pixel_values: torch.Tensor, use_video_patch_projection: bool = False) -> torch.Tensor: | |||
| 168 | projection = self.video_patch_projection if use_video_patch_projection else self.patch_projection | |||
| 169 | patches = projection(self._image_to_patches(pixel_values)) | |||
| 170 | input_dims = (pixel_values.shape[-2] // self.patch_size, pixel_values.shape[-1] // self.patch_size) | |||
| 171 | patches = patches + self._interpolate_position_embedding(input_dims, patches.dtype) | |||
| 172 | prefix = self.cls_register_token.unsqueeze(0).expand(patches.shape[0], -1, -1) | |||
| 173 | return torch.cat([prefix, patches], dim=1) | |||
| 174 | ||||
| 175 | ||||
| 176 | class RadioMLP(nn.Module): | |||
| 177 | def __init__(self, config) -> None: | |||
| 178 | super().__init__() | |||
| 179 | in_features = out_features = config.hidden_size | |||
| 180 | hidden_features = int(config.hidden_size * config.mlp_ratio) | |||
| 181 | self.fc1 = nn.Linear(in_features, hidden_features, bias=True) | |||
| 182 | if isinstance(config.hidden_act, str): | |||
| 183 | self.activation = ACT2FN[config.hidden_act] | |||
| 184 | else: | |||
| 185 | self.activation = config.hidden_act | |||
| 186 | self.fc2 = nn.Linear(hidden_features, out_features, bias=True) | |||
| 187 | ||||
| 188 | def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: | |||
| 189 | hidden_state = self.fc1(hidden_state) | |||
| 190 | hidden_state = self.activation(hidden_state) | |||
| 191 | hidden_state = self.fc2(hidden_state) | |||
| 192 | return hidden_state | |||
| 193 | ||||
| 194 | ||||
| 195 | class RadioLayerScale(nn.Module): | |||
| 196 | def __init__(self, config) -> None: | |||
| 197 | super().__init__() | |||
| 198 | self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size)) | |||
| 199 | ||||
| 200 | def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: | |||
| 201 | return hidden_state * self.lambda1 | |||
| 202 | ||||
| 203 | ||||
| 204 | def eager_attention_forward( | |||
| 205 | module: nn.Module, | |||
| 206 | query: torch.Tensor, | |||
| 207 | key: torch.Tensor, | |||
| 208 | value: torch.Tensor, | |||
| 209 | attention_mask: torch.Tensor | None, | |||
| 210 | scaling: float | None = None, | |||
| 211 | dropout: float = 0.0, | |||
| 212 | **kwargs: Unpack[TransformersKwargs], | |||
| 213 | ): | |||
| 214 | if scaling is None: | |||
| 215 | scaling = query.size(-1) ** -0.5 | |||
| 216 | ||||
| 217 | # Take the dot product between "query" and "key" to get the raw attention scores. | |||
| 218 | attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling | |||
| 219 | ||||
| 220 | if attention_mask is not None: | |||
| 221 | attn_weights = attn_weights + attention_mask | |||
| 222 | ||||
| 223 | attn_weights = nn.functional.softmax(attn_weights, dim=-1) | |||
| 224 | attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) | |||
| 225 | ||||
| 226 | attn_output = torch.matmul(attn_weights, value) | |||
| 227 | attn_output = attn_output.transpose(1, 2).contiguous() | |||
| 228 | ||||
| 229 | return attn_output, attn_weights | |||
| 230 | ||||
| 231 | ||||
| 232 | # Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Radio | |||
| 233 | class RadioSelfAttention(nn.Module): | |||
| 234 | def __init__(self, config: RadioConfig): | |||
| 235 | super().__init__() | |||
| 236 | if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): | |||
| 237 | raise ValueError( | |||
| 238 | f"The hidden size {config.hidden_size} is not a multiple of the number of attention " | |||
| 239 | f"heads {config.num_attention_heads}." | |||
| 240 | ) | |||
| 241 | ||||
| 242 | self.config = config | |||
| 243 | self.num_attention_heads = config.num_attention_heads | |||
| 244 | self.attention_head_size = int(config.hidden_size / config.num_attention_heads) | |||
| 245 | self.all_head_size = self.num_attention_heads * self.attention_head_size | |||
| 246 | self.dropout_prob = config.attention_probs_dropout_prob | |||
| 247 | self.scaling = self.attention_head_size**-0.5 | |||
| 248 | self.is_causal = False | |||
| 249 | ||||
| 250 | self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) | |||
| 251 | self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) | |||
| 252 | self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) | |||
| 253 | ||||
| 254 | def forward( | |||
| 255 | self, | |||
| 256 | hidden_states: torch.Tensor, | |||
| 257 | **kwargs: Unpack[TransformersKwargs], | |||
| 258 | ) -> tuple[torch.Tensor, torch.Tensor]: | |||
| 259 | batch_size = hidden_states.shape[0] | |||
| 260 | new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size | |||
| 261 | ||||
| 262 | key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2) | |||
| 263 | value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2) | |||
| 264 | query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2) | |||
| 265 | ||||
| 266 | attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( | |||
| 267 | self.config._attn_implementation, eager_attention_forward | |||
| 268 | ) | |||
| 269 | ||||
| 270 | context_layer, attention_probs = attention_interface( | |||
| 271 | self, | |||
| 272 | query_layer, | |||
| 273 | key_layer, | |||
| 274 | value_layer, | |||
| 275 | None, | |||
| 276 | is_causal=self.is_causal, | |||
| 277 | scaling=self.scaling, | |||
| 278 | dropout=0.0 if not self.training else self.dropout_prob, | |||
| 279 | **kwargs, | |||
| 280 | ) | |||
| 281 | ||||
| 282 | new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) | |||
| 283 | context_layer = context_layer.reshape(new_context_layer_shape) | |||
| 284 | ||||
| 285 | return context_layer, attention_probs | |||
| 286 | ||||
| 287 | ||||
| 288 | # Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Radio | |||
| 289 | class RadioSelfOutput(nn.Module): | |||
| 290 | """ | |||
| 291 | The residual connection is defined in RadioLayer instead of here (as is the case with other models), due to the | |||
| 292 | layernorm applied before each block. | |||
| 293 | """ | |||
| 294 | ||||
| 295 | def __init__(self, config: RadioConfig): | |||
| 296 | super().__init__() | |||
| 297 | self.dense = nn.Linear(config.hidden_size, config.hidden_size) | |||
| 298 | self.dropout = nn.Dropout(config.hidden_dropout_prob) | |||
| 299 | ||||
| 300 | def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: | |||
| 301 | hidden_states = self.dense(hidden_states) | |||
| 302 | hidden_states = self.dropout(hidden_states) | |||
| 303 | return hidden_states | |||
| 304 | ||||
| 305 | ||||
| 306 | # Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Radio | |||
| 307 | class RadioAttention(nn.Module): | |||
| 308 | def __init__(self, config: RadioConfig): | |||
| 309 | super().__init__() | |||
| 310 | self.attention = RadioSelfAttention(config) | |||
| 311 | self.output = RadioSelfOutput(config) | |||
| 312 | ||||
| 313 | def forward( | |||
| 314 | self, | |||
| 315 | hidden_states: torch.Tensor, | |||
| 316 | **kwargs: Unpack[TransformersKwargs], | |||
| 317 | ) -> torch.Tensor: | |||
| 318 | self_attn_output, _ = self.attention(hidden_states, **kwargs) | |||
| 319 | output = self.output(self_attn_output, hidden_states) | |||
| 320 | return output | |||
| 321 | ||||
| 322 | ||||
| 323 | class RadioSwiGLUFFN(nn.Module): | |||
| 324 | def __init__(self, config) -> None: | |||
| 325 | super().__init__() | |||
| 326 | in_features = out_features = config.hidden_size | |||
| 327 | hidden_features = int(config.hidden_size * config.mlp_ratio) | |||
| 328 | hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 | |||
| 329 | ||||
| 330 | self.weights_in = nn.Linear(in_features, 2 * hidden_features, bias=True) | |||
| 331 | self.weights_out = nn.Linear(hidden_features, out_features, bias=True) | |||
| 332 | ||||
| 333 | def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: | |||
| 334 | hidden_state = self.weights_in(hidden_state) | |||
| 335 | x1, x2 = hidden_state.chunk(2, dim=-1) | |||
| 336 | hidden = nn.functional.silu(x1) * x2 | |||
| 337 | return self.weights_out(hidden) | |||
| 338 | ||||
| 339 | ||||
| 340 | class RadioDropPath(nn.Module): | |||
| 341 | """Stochastic depth (DropPath) per sample, for residual blocks. | |||
| 342 | ||||
| 343 | Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth | |||
| 344 | <https://arxiv.org/abs/1603.09382>`_. | |||
| 345 | """ | |||
| 346 | ||||
| 347 | def __init__(self, drop_prob: float = 0.0) -> None: | |||
| 348 | super().__init__() | |||
| 349 | self.drop_prob = drop_prob | |||
| 350 | ||||
| 351 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: | |||
| 352 | if self.drop_prob == 0.0 or not self.training: | |||
| 353 | return hidden_states | |||
| 354 | keep_prob = 1 - self.drop_prob | |||
| 355 | shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1) | |||
| 356 | random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device) | |||
| 357 | random_tensor = torch.floor(random_tensor + keep_prob) | |||
| 358 | return hidden_states.div(keep_prob) * random_tensor | |||
| 359 | ||||
| 360 | def extra_repr(self) -> str: | |||
| 361 | return f"p={self.drop_prob}" | |||
| 362 | ||||
| 363 | ||||
| 364 | class RadioLayer(GradientCheckpointingLayer): | |||
| 365 | """This corresponds to the Block class in the original implementation.""" | |||
| 366 | ||||
| 367 | def __init__(self, config: RadioConfig) -> None: | |||
| 368 | super().__init__() | |||
| 369 | ||||
| 370 | self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) | |||
| 371 | self.attention = RadioAttention(config) | |||
| 372 | self.layer_scale1 = RadioLayerScale(config) | |||
| 373 | self.drop_path = RadioDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity() | |||
| 374 | ||||
| 375 | self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) | |||
| 376 | ||||
| 377 | if config.use_swiglu_ffn: | |||
| 378 | self.mlp = RadioSwiGLUFFN(config) | |||
| 379 | else: | |||
| 380 | self.mlp = RadioMLP(config) | |||
| 381 | self.layer_scale2 = RadioLayerScale(config) | |||
| 382 | ||||
| 383 | def forward( | |||
| 384 | self, | |||
| 385 | hidden_states: torch.Tensor, | |||
| 386 | ) -> torch.Tensor: | |||
| 387 | hidden_states_norm = self.norm1(hidden_states) | |||
| 388 | self_attention_output = self.attention(hidden_states_norm) | |||
| 389 | self_attention_output = self.layer_scale1(self_attention_output) | |||
| 390 | ||||
| 391 | # first residual connection | |||
| 392 | hidden_states = self.drop_path(self_attention_output) + hidden_states | |||
| 393 | ||||
| 394 | # in Radio, layernorm is also applied after self-attention | |||
| 395 | layer_output = self.norm2(hidden_states) | |||
| 396 | layer_output = self.mlp(layer_output) | |||
| 397 | layer_output = self.layer_scale2(layer_output) | |||
| 398 | ||||
| 399 | # second residual connection | |||
| 400 | layer_output = self.drop_path(layer_output) + hidden_states | |||
| 401 | ||||
| 402 | return layer_output | |||
| 403 | ||||
| 404 | ||||
| 405 | @auto_docstring | |||
| 406 | class RadioPreTrainedModel(PreTrainedModel): | |||
| 407 | config_class = RadioConfig | |||
| 408 | base_model_prefix = "model" | |||
| 409 | main_input_name = "pixel_values" | |||
| 410 | supports_gradient_checkpointing = True | |||
| 411 | _no_split_modules = ["RadioLayer"] | |||
| 412 | _keys_to_ignore_on_load_missing = [r"layer_scale\d+\.lambda1"] | |||
| 413 | _supports_sdpa = True | |||
| 414 | _supports_flash_attn = True | |||
| 415 | _can_record_outputs = { | |||
| 416 | "hidden_states": RadioLayer, | |||
| 417 | "attentions": RadioSelfAttention, | |||
| 418 | } | |||
| 419 | ||||
| 420 | @torch.no_grad() | |||
| 421 | def _init_weights(self, module): | |||
| 422 | # Use `transformers.initialization` (not in-place `.data` ops) so the | |||
| 423 | # framework's `_is_hf_initialized` guard skips already-loaded params. | |||
| 424 | std = self.config.initializer_range | |||
| 425 | if isinstance(module, nn.Linear): | |||
| 426 | init.trunc_normal_(module.weight, mean=0.0, std=std) | |||
| 427 | if module.bias is not None: | |||
| 428 | init.zeros_(module.bias) | |||
| 429 | elif isinstance(module, nn.LayerNorm): | |||
| 430 | init.zeros_(module.bias) | |||
| 431 | init.ones_(module.weight) | |||
| 432 | elif isinstance(module, RadioPatchEmbeddings): | |||
| 433 | init.trunc_normal_(module.position_embedding, mean=0.0, std=std) | |||
| 434 | init.trunc_normal_(module.cls_register_token, mean=0.0, std=std) | |||
| 435 | elif isinstance(module, RadioLayerScale): | |||
| 436 | init.constant_(module.lambda1, self.config.layerscale_value) | |||
| 437 | elif isinstance(module, RadioInputConditioner): | |||
| 438 | init.copy_(module.norm_mean, torch.tensor(self.config.norm_mean).view(-1, 1, 1)) | |||
| 439 | init.copy_(module.norm_std, torch.tensor(self.config.norm_std).view(-1, 1, 1)) | |||
| 440 | elif isinstance(module, RadioModel): | |||
| 441 | init.copy_(module.summary_idxs, torch.tensor(self.config.summary_idxs, dtype=torch.long)) | |||
| 442 | ||||
| 443 | ||||
| 444 | class RadioEncoder(RadioPreTrainedModel): | |||
| 445 | def __init__(self, config: RadioConfig): | |||
| 446 | super().__init__(config) | |||
| 447 | self.layer = nn.ModuleList([RadioLayer(config) for _ in range(config.num_hidden_layers)]) | |||
| 448 | self.post_init() | |||
| 449 | ||||
| 450 | @merge_with_config_defaults | |||
| 451 | @capture_outputs(tie_last_hidden_states=False) | |||
| 452 | def forward(self, hidden_states: torch.Tensor, **kwargs: Unpack[TransformersKwargs]) -> BaseModelOutput: | |||
| 453 | for layer in self.layer: | |||
| 454 | hidden_states = layer(hidden_states) | |||
| 455 | return BaseModelOutput(last_hidden_state=hidden_states) | |||
| 456 | ||||
| 457 | ||||
| 458 | @auto_docstring | |||
| 459 | class RadioModel(RadioPreTrainedModel): | |||
| 460 | def __init__(self, config: RadioConfig): | |||
| 461 | super().__init__(config) | |||
| 462 | register_radio_conversion_mapping() | |||
| 463 | self.config = config | |||
| 464 | self.input_conditioner = RadioInputConditioner(config) | |||
| 465 | self.embeddings = RadioPatchEmbeddings(config) | |||
| 466 | self.encoder = RadioEncoder(config) | |||
| 467 | self.register_buffer("summary_idxs", torch.tensor(config.summary_idxs, dtype=torch.long), persistent=True) | |||
| 468 | self.post_init() | |||
| 469 | ||||
| 470 | @property | |||
| 471 | def patch_size(self) -> int: | |||
| 472 | return self.config.patch_size | |||
| 473 | ||||
| 474 | def make_preprocessor_external(self): | |||
| 475 | """Detach the input conditioner (caller applies normalization itself).""" | |||
| 476 | conditioner = self.input_conditioner | |||
| 477 | self.input_conditioner = nn.Identity() | |||
| 478 | return conditioner | |||
| 479 | ||||
| 480 | @can_return_tuple | |||
| 481 | @auto_docstring | |||
| 482 | def forward( | |||
| 483 | self, | |||
| 484 | pixel_values: torch.Tensor, | |||
| 485 | use_video_patch_projection: bool = False, | |||
| 486 | **kwargs: Unpack[TransformersKwargs], | |||
| 487 | ) -> RadioModelOutput: | |||
| 488 | r""" | |||
| 489 | use_video_patch_projection (`bool`, *optional*, defaults to `False`): | |||
| 490 | Use the `video_patch_projection` for temporally-packed video patches instead of the image | |||
| 491 | `patch_projection`. Requires `config.video_temporal_patch_size` to be set. | |||
| 492 | """ | |||
| 493 | pixel_values = self.input_conditioner(pixel_values) | |||
| 494 | hidden_states = self.embeddings(pixel_values, use_video_patch_projection=use_video_patch_projection) | |||
| 495 | encoder_outputs: BaseModelOutput = self.encoder(hidden_states, **kwargs) | |||
| 496 | last_hidden_state = encoder_outputs.last_hidden_state | |||
| 497 | ||||
| 498 | num_skip = self.config.num_summary_tokens | |||
| 499 | all_summary = last_hidden_state[:, : self.config.num_cls_tokens] | |||
| 500 | summary = all_summary[:, self.summary_idxs].flatten(1) | |||
| 501 | features = last_hidden_state[:, num_skip:] | |||
| 502 | ||||
| 503 | return RadioModelOutput( | |||
| 504 | summary=summary, | |||
| 505 | features=features, | |||
| 506 | last_hidden_state=last_hidden_state, | |||
| 507 | hidden_states=encoder_outputs.hidden_states, | |||
| 508 | attentions=encoder_outputs.attentions, | |||
| 509 | ) | |||
| 510 | ||||
| 511 | ||||
| 512 | __all__ = ["RadioModel", "RadioPreTrainedModel"] |