Run this model with HF Jobs
Run nvidia/C-RADIOv4-SO400M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/nvidia/C-RADIOv4-SO400M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/nvidia/C-RADIOv4-SO400M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use nvidia/C-RADIOv4-SO400M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nvidia/C-RADIOv4-SO400M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="nvidia/C-RADIOv4-SO400M", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("nvidia/C-RADIOv4-SO400M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload model
#3
by mranzinger - opened
Files changed (7)
- adaptor_attn.pyAdded+48
- adaptor_base.py+13
- adaptor_generic.py+1-1
- adaptor_mlp.py+4-121
- adaptor_module_factory.pyAdded+96
- common.py+1-1
- hf_model.py+3-1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.## NVIDIA CORPORATION and its licensors retain all intellectual property# and proprietary rights in and to this software, related documentation# and any modifications thereto. Any use, reproduction, disclosure or# distribution of this software and related documentation without an express# license agreement from NVIDIA CORPORATION is strictly prohibited.import mathfrom typing import Dict, Optional
import torchfrom torch import nn
from einops import rearrangefrom timm.models.vision_transformer import Block
from .enable_spectral_reparam import disable_spectral_reparam, enable_spectral_reparamfrom .adaptor_base import AdaptorModuleBasefrom .adaptor_mlp import MLP2
class AttnFDHead(AdaptorModuleBase): def __init__( self, input_size: int, hidden_size: int, output_size: int, num_inner: int = 0, pre_norm: bool = False, device: torch.device = None, upsample_factor: int = 1, upsample_rank: int = 0, **kwargs # Ignore kwargs that might be to other "mlp" verions, e.g. teacher_summary_idxs ) -> None: super().__init__(requires_summary_and_spatial=False) from timm.models.vision_transformer import Block self.blocks = nn.Sequential(*[ Block(input_size, num_heads=16, init_values=1e-5) for _ in range(2) ]) self.mlp = MLP2(input_size, hidden_size, output_size, num_inner=0, pre_norm=pre_norm, device=device, upsample_factor=upsample_factor, upsample_rank=upsample_rank, **kwargs)
def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: x = self.blocks(x) x = self.mlp(x) return x31 unmodified lines32333435363731 unmodified lines)class AdaptorBase(nn.Module):def forward(self, input: AdaptorInput) -> RadioOutput:raise NotImplementedError("Subclasses must implement this!")31 unmodified lines3233343536373839404142434445464748495031 unmodified lines)class AdaptorModuleBase(nn.Module):def __init__(self,requires_summary_and_spatial: bool,handles_summary_and_spatial: bool = False) -> None:super().__init__()self.requires_summary_and_spatial = requires_summary_and_spatialself.handles_summary_and_spatial = handles_summary_and_spatialassert not handles_summary_and_spatial or requires_summary_and_spatial, "If handles summary and spatial, must require it too!"class AdaptorBase(nn.Module):def forward(self, input: AdaptorInput) -> RadioOutput:raise NotImplementedError("Subclasses must implement this!")
11 unmodified lines1213141516171811 unmodified linesimport torch.nn.functional as Ffrom .adaptor_base import AdaptorBase, AdaptorInput, RadioOutputfrom .adaptor_mlp import create_mlp_from_state, create_mlp_from_configclass GenericAdaptor(AdaptorBase):11 unmodified lines1213141516171811 unmodified linesimport torch.nn.functional as Ffrom .adaptor_base import AdaptorBase, AdaptorInput, RadioOutputfrom .adaptor_module_factory import create_mlp_from_state, create_mlp_from_configclass GenericAdaptor(AdaptorBase):
123410 unmodified lines15161718192021222324252627282930313233343524 unmodified lines6061626364656651 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.## NVIDIA CORPORATION and its licensors retain all intellectual property# and proprietary rights in and to this software, related documentation10 unmodified linesfrom timm.models.vision_transformer import Blockfrom .enable_spectral_reparam import disable_spectral_reparam, enable_spectral_reparamclass MLPBase(nn.Module):def __init__(self,requires_summary_and_spatial: bool,handles_summary_and_spatial: bool = False) -> None:super().__init__()self.requires_summary_and_spatial = requires_summary_and_spatialself.handles_summary_and_spatial = handles_summary_and_spatialassert not handles_summary_and_spatial or requires_summary_and_spatial, "If handles summary and spatial, must require it too!"class MLP(MLPBase):def __init__(self, input_size: int, hidden_size: int, output_size: int,num_inner: int = 0, device: torch.device = None, **kwargs):super(MLP, self).__init__(requires_summary_and_spatial=False)24 unmodified linesreturn xclass MLP2(MLPBase):def __init__(self, input_size: int, hidden_size: int, output_size: int,num_inner: int = 0,pre_norm: bool = False, device: torch.device = None,51 unmodified linesc=self._real_output_dim)return xclass AttnFDHead(MLPBase):def __init__(self,input_size: int,hidden_size: int,output_size: int,num_inner: int = 0,pre_norm: bool = False,device: torch.device = None,upsample_factor: int = 1,upsample_rank: int = 0,**kwargs # Ignore kwargs that might be to other "mlp" verions, e.g. teacher_summary_idxs) -> None:super().__init__(requires_summary_and_spatial=False)from timm.models.vision_transformer import Blockself.blocks = nn.Sequential(*[Block(input_size, num_heads=16, init_values=1e-5)for _ in range(2)])self.mlp = MLP2(input_size, hidden_size, output_size,num_inner=0, pre_norm=pre_norm, device=device,upsample_factor=upsample_factor, upsample_rank=upsample_rank, **kwargs)def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor:x = self.blocks(x)x = self.mlp(x)return xMLP_SUMMARY_FACTORY = {'v1': MLP,'v2': MLP2,}MLP_FD_FACTORY = {'v1': MLP,'v2': MLP2,'attn': AttnFDHead,}def strip_prefix(state: Dict[str, torch.Tensor], prefix: str):state = {k[len(prefix):]: vfor k, v in state.items()if k.startswith(prefix)}return statedef get_mlp_info_from_state(version: str, state: Dict[str, torch.Tensor], prefix: str = '', spectral_weights: bool = False):state = strip_prefix(state, prefix)weight_suffix = 'weight' if not spectral_weights else 'parametrizations.weight.original'if version == 'v1':hidden_dim, input_dim = state[f'fc1.{weight_suffix}'].shapeoutput_dim = state[f'fc2.{weight_suffix}'].shape[0]for num_inner in range(1000):k = f'inner.{num_inner}.0.weight'if k not in state:breakelif version == 'v2':hidden_dim, input_dim = state[f'fc1.{weight_suffix}'].shapeoutput_dim = state[f'final.2.{weight_suffix}'].shape[0]for num_inner in range(1000):k = f'blocks.{num_inner}.0.weight'if k not in state:breakelif version == 'attn':hidden_dim, input_dim = state[f'mlp.fc1.{weight_suffix}'].shapeoutput_dim = state[f'mlp.final.2.{weight_suffix}'].shape[0]num_inner = 0else:raise ValueError(f'Unsupported MLP version: {version}')return input_dim, hidden_dim, output_dim, num_innerdef create_mlp_from_config(version: str, input_dim: int, hidden_dim: int, output_dim: int, num_inner: int, is_summary: bool = True, **kwargs):factory = MLP_SUMMARY_FACTORY if is_summary else MLP_FD_FACTORYret: nn.Module = factory[version](input_dim, hidden_dim, output_dim, num_inner, from_config=True, **kwargs)return retdef create_mlp_from_state(version: str, state: Dict[str, torch.Tensor], prefix: str = '', spectral_weights: bool = False, is_summary: bool = True, **kwargs):state = strip_prefix(state, prefix)input_dim, hidden_dim, output_dim, num_inner = get_mlp_info_from_state(version, state, spectral_weights=spectral_weights)ret: nn.Module = create_mlp_from_config(version, input_dim, hidden_dim, output_dim, num_inner, is_summary=is_summary, **kwargs)if spectral_weights:enable_spectral_reparam(ret, init_norm_to_current=False, state_dict_guidance=state)ret.load_state_dict(state)if spectral_weights:disable_spectral_reparam(ret)return ret123410 unmodified lines1516171819202122232424 unmodified lines4950515253545551 unmodified lines107108109# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.## NVIDIA CORPORATION and its licensors retain all intellectual property# and proprietary rights in and to this software, related documentation10 unmodified linesfrom timm.models.vision_transformer import Blockfrom .enable_spectral_reparam import disable_spectral_reparam, enable_spectral_reparamfrom .adaptor_base import AdaptorModuleBaseclass MLP(AdaptorModuleBase):def __init__(self, input_size: int, hidden_size: int, output_size: int,num_inner: int = 0, device: torch.device = None, **kwargs):super(MLP, self).__init__(requires_summary_and_spatial=False)24 unmodified linesreturn xclass MLP2(AdaptorModuleBase):def __init__(self, input_size: int, hidden_size: int, output_size: int,num_inner: int = 0,pre_norm: bool = False, device: torch.device = None,51 unmodified linesc=self._real_output_dim)return x
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.## NVIDIA CORPORATION and its licensors retain all intellectual property# and proprietary rights in and to this software, related documentation# and any modifications thereto. Any use, reproduction, disclosure or# distribution of this software and related documentation without an express# license agreement from NVIDIA CORPORATION is strictly prohibited.import mathfrom typing import Dict, Optional
import torchfrom torch import nn
from einops import rearrangefrom timm.models.vision_transformer import Block
from .enable_spectral_reparam import disable_spectral_reparam, enable_spectral_reparamfrom .adaptor_mlp import MLP, MLP2from .adaptor_attn import AttnFDHead
MLP_SUMMARY_FACTORY = { 'v1': MLP, 'v2': MLP2,}
MLP_FD_FACTORY = { 'v1': MLP, 'v2': MLP2, 'attn': AttnFDHead,}
def strip_prefix(state: Dict[str, torch.Tensor], prefix: str): state = { k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix) } return state
def get_mlp_info_from_state(version: str, state: Dict[str, torch.Tensor], prefix: str = '', spectral_weights: bool = False): state = strip_prefix(state, prefix)
weight_suffix = 'weight' if not spectral_weights else 'parametrizations.weight.original'
if version == 'v1': hidden_dim, input_dim = state[f'fc1.{weight_suffix}'].shape output_dim = state[f'fc2.{weight_suffix}'].shape[0]
for num_inner in range(1000): k = f'inner.{num_inner}.0.weight' if k not in state: break elif version == 'v2': hidden_dim, input_dim = state[f'fc1.{weight_suffix}'].shape output_dim = state[f'final.2.{weight_suffix}'].shape[0]
for num_inner in range(1000): k = f'blocks.{num_inner}.0.weight' if k not in state: break elif version == 'attn': hidden_dim, input_dim = state[f'mlp.fc1.{weight_suffix}'].shape output_dim = state[f'mlp.final.2.{weight_suffix}'].shape[0] num_inner = 0 else: raise ValueError(f'Unsupported MLP version: {version}')
return input_dim, hidden_dim, output_dim, num_inner
def create_mlp_from_config(version: str, input_dim: int, hidden_dim: int, output_dim: int, num_inner: int, is_summary: bool = True, **kwargs): factory = MLP_SUMMARY_FACTORY if is_summary else MLP_FD_FACTORY
ret: nn.Module = factory[version](input_dim, hidden_dim, output_dim, num_inner, from_config=True, **kwargs)
return ret
def create_mlp_from_state(version: str, state: Dict[str, torch.Tensor], prefix: str = '', spectral_weights: bool = False, is_summary: bool = True, **kwargs): state = strip_prefix(state, prefix)
input_dim, hidden_dim, output_dim, num_inner = get_mlp_info_from_state(version, state, spectral_weights=spectral_weights)
ret: nn.Module = create_mlp_from_config(version, input_dim, hidden_dim, output_dim, num_inner, is_summary=is_summary, **kwargs) if spectral_weights: enable_spectral_reparam(ret, init_norm_to_current=False, state_dict_guidance=state)
ret.load_state_dict(state)
if spectral_weights: disable_spectral_reparam(ret)
return ret145 unmodified lines146147148149150151152145 unmodified lines"c-radio_v4-so400m": RadioResource(# NOTE: C-RADIO models are bound by different license terms than that present in the LICENSE file.# Please refer to the readme, or to https://huggingface.co/nvidia/C-RADIOv4-SO400M for more information."https://huggingface.co/nvidia/C-RADIOv4-SO400M/resolve/main/c-radio-v4-so400m_half.pth.tar?download=true",patch_size=16,max_resolution=2048,preferred_resolution=Resolution(512, 512),145 unmodified lines146147148149150151152145 unmodified lines"c-radio_v4-so400m": RadioResource(# NOTE: C-RADIO models are bound by different license terms than that present in the LICENSE file.# Please refer to the readme, or to https://huggingface.co/nvidia/C-RADIOv4-SO400M for more information."https://huggingface.co/nvidia/C-RADIOv4-SO400M/resolve/main/c-radio_v4-so400m_half.pth.tar?download=true",patch_size=16,max_resolution=2048,preferred_resolution=Resolution(512, 512),
24 unmodified lines2526272829303124 unmodified lines# Import all required modules.from .adaptor_base import AdaptorBase, RadioOutput, AdaptorInputfrom .adaptor_generic import GenericAdaptor, AdaptorBasefrom .adaptor_mlp import create_mlp_from_configfrom .adaptor_registry import adaptor_registryfrom .cls_token import ClsTokenfrom .dinov2_arch import dinov2_vitg14_reg24 unmodified lines25262728293031323324 unmodified lines# Import all required modules.from .adaptor_base import AdaptorBase, RadioOutput, AdaptorInputfrom .adaptor_generic import GenericAdaptor, AdaptorBasefrom .adaptor_module_factory import create_mlp_from_configfrom .adaptor_mlp import MLP, MLP2from .adaptor_attn import AttnFDHeadfrom .adaptor_registry import adaptor_registryfrom .cls_token import ClsTokenfrom .dinov2_arch import dinov2_vitg14_reg
adaptor_attn.pyAdded+48
adaptor_base.py+13
adaptor_generic.py+1-1
adaptor_mlp.py+4-121
adaptor_module_factory.pyAdded+96
common.py+1-1
hf_model.py+3-1