Instructions to use nvidia/RADIO-L with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nvidia/RADIO-L with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-feature-extraction", model="nvidia/RADIO-L", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("nvidia/RADIO-L", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload model
Browse filesFiles changed (19)
- README.mdAdded+199
- adaptor_base.pyAdded+35
- adaptor_generic.pyAdded+29
- adaptor_mlp.pyAdded+150
- adaptor_registry.pyAdded+37
- cls_token.pyAdded+55
- common.pyAdded+71
- config.jsonAdded+221
- enable_cpe_support.pyAdded+158
- enable_spectral_reparam.pyAdded+227
- eradio_model.pyAdded+1392
- extra_timm_models.pyAdded+66
- hf_model.pyAdded+174
- input_conditioner.pyAdded+49
- model.safetensorsAdded+3
- open_clip_adaptor.pyAdded+41
- radio_model.pyAdded+257
- vit_patch_generator.pyAdded+299
- vitdet.pyAdded+181
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199---library_name: transformerstags: []---
# Model Card for Model ID
<!-- Provide a quick summary of what the model is/does. -->
## Model Details
### Model Description
<!-- Provide a longer summary of what this model is. -->
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### Model Sources [optional]
<!-- Provide the basic links for the model. -->
- **Repository:** [More Information Needed]- **Paper [optional]:** [More Information Needed]- **Demo [optional]:** [More Information Needed]
## Uses
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
### Direct Use
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
### Downstream Use [optional]
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
[More Information Needed]
### Out-of-Scope Use
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
[More Information Needed]
## Bias, Risks, and Limitations
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
[More Information Needed]
### Recommendations
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
## How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
## Training Details
### Training Data
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
[More Information Needed]
### Training Procedure
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
#### Preprocessing [optional]
[More Information Needed]
#### Training Hyperparameters
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
#### Speeds, Sizes, Times [optional]
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
[More Information Needed]
## Evaluation
<!-- This section describes the evaluation protocols and provides the results. -->
### Testing Data, Factors & Metrics
#### Testing Data
<!-- This should link to a Dataset Card if possible. -->
[More Information Needed]
#### Factors
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
[More Information Needed]
#### Metrics
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
[More Information Needed]
### Results
[More Information Needed]
#### Summary
## Model Examination [optional]
<!-- Relevant interpretability work for the model goes here -->
[More Information Needed]
## Environmental Impact
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
- **Hardware Type:** [More Information Needed]- **Hours used:** [More Information Needed]- **Cloud Provider:** [More Information Needed]- **Compute Region:** [More Information Needed]- **Carbon Emitted:** [More Information Needed]
## Technical Specifications [optional]
### Model Architecture and Objective
[More Information Needed]
### Compute Infrastructure
[More Information Needed]
#### Hardware
[More Information Needed]
#### Software
[More Information Needed]
## Citation [optional]
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
**BibTeX:**
[More Information Needed]
**APA:**
[More Information Needed]
## Glossary [optional]
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
[More Information Needed]
## More Information [optional]
[More Information Needed]
## Model Card Authors [optional]
[More Information Needed]
## Model Card Contact
[More Information Needed]1234567891011121314151617181920212223242526272829303132333435# 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 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.from argparse import Namespacefrom typing import NamedTuple
import torchfrom torch import nnimport torch.nn.functional as F
class AdaptorInput(NamedTuple): images: torch.Tensor summary: torch.Tensor features: torch.Tensor
class RadioOutput(NamedTuple): summary: torch.Tensor features: torch.Tensor
def to(self, *args, **kwargs): return RadioOutput( self.summary.to(*args, **kwargs) if self.summary is not None else None, self.features.to(*args, **kwargs) if self.features is not None else None, )
class AdaptorBase(nn.Module): def forward(self, input: AdaptorInput) -> RadioOutput: raise NotImplementedError("Subclasses must implement this!")1234567891011121314151617181920212223242526272829# 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 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.from argparse import Namespace
import torchfrom torch import nnimport torch.nn.functional as F
from .adaptor_base import AdaptorBase, AdaptorInput, RadioOutputfrom .adaptor_mlp import create_mlp_from_state
class GenericAdaptor(AdaptorBase): def __init__(self, main_config: Namespace, adaptor_config, state): super().__init__()
self.head_mlp = create_mlp_from_state(main_config.mlp_version, state, 'summary.') self.feat_mlp = create_mlp_from_state(main_config.mlp_version, state, 'feature.')
def forward(self, input: AdaptorInput) -> RadioOutput: summary = self.head_mlp(input.summary) feat = self.feat_mlp(input.features)
return RadioOutput(summary, feat)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# 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 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
import torchfrom torch import nn
from einops import rearrangefrom timm.models.vision_transformer import Block
class MLP(nn.Module): 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__() self.fc1 = nn.Linear(input_size, hidden_size, device=device) self.norm = nn.LayerNorm(hidden_size, device=device) self.relu = nn.ReLU()
inner = [] for _ in range(num_inner): inner.extend([ nn.Linear(hidden_size, hidden_size, device=device), nn.LayerNorm(hidden_size, device=device), nn.ReLU(), ]) if inner: self.inner = nn.Sequential(*inner) else: self.inner = nn.Identity()
self.fc2 = nn.Linear(hidden_size, output_size, device=device)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.fc1(x) x = self.norm(x) x = self.relu(x) x = self.inner(x) x = self.fc2(x) return x
class MLP2(nn.Module): 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, **kwargs): super().__init__()
self.pre_norm = nn.Sequential( nn.LayerNorm(input_size), nn.GELU(), ) if pre_norm else nn.Identity()
self.upsample_factor = upsample_factor self._real_output_dim = output_size
hidden_size *= upsample_factor output_size *= (upsample_factor ** 2)
self.fc1 = nn.Linear(input_size, hidden_size, device=device)
blocks = [] for _ in range(num_inner): blocks.append(nn.Sequential( nn.LayerNorm(hidden_size, device=device), nn.GELU(), nn.Linear(hidden_size, hidden_size, device=device), )) self.blocks = nn.ModuleList(blocks)
self.final = nn.Sequential( nn.LayerNorm(hidden_size, device=device), nn.GELU(), nn.Linear(hidden_size, output_size, device=device), )
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.pre_norm(x) x = self.fc1(x) for block in self.blocks: x = x + block(x) x = self.final(x)
if self.upsample_factor > 1: h = w = int(math.sqrt(x.shape[1])) x = rearrange(x, 'b (h w) (u1 u2 c) -> b (u1 h u2 w) c', h=h, w=w, u1=self.upsample_factor, u2=self.upsample_factor, c=self._real_output_dim)
return x
MLP_FACTORY = { 'v1': MLP, 'v2': MLP2,}
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 = ''): state = strip_prefix(state, prefix)
if version == 'v1': hidden_dim, input_dim = state['fc1.weight'].shape output_dim = state['fc2.weight'].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['fc1.weight'].shape output_dim = state['final.2.weight'].shape[0]
for num_inner in range(1000): k = f'blocks.{num_inner}.0.weight' if k not in state: break else: raise ValueError(f'Unsupported MLP version: {version}')
return input_dim, hidden_dim, output_dim, num_inner
def create_mlp_from_state(version: str, state: Dict[str, torch.Tensor], prefix: str = ''): state = strip_prefix(state, prefix)
input_dim, hidden_dim, output_dim, num_inner = get_mlp_info_from_state(version, state)
ret: nn.Module = MLP_FACTORY[version](input_dim, hidden_dim, output_dim, num_inner)
ret.load_state_dict(state)
return ret12345678910111213141516171819202122232425262728293031323334353637# 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 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.from argparse import Namespacefrom typing import Dict, Any
import torch
from .adaptor_generic import GenericAdaptor, AdaptorBase
dict_t = Dict[str, Any]state_t = Dict[str, torch.Tensor]
class AdaptorRegistry: def __init__(self): self._registry = {}
def register_adaptor(self, name): def decorator(factory_function): if name in self._registry: raise ValueError(f"Model '{name}' already registered") self._registry[name] = factory_function return factory_function return decorator
def create_adaptor(self, name, main_config: Namespace, adaptor_config: dict_t, state: state_t) -> AdaptorBase: if name not in self._registry: return GenericAdaptor(main_config, adaptor_config, state) return self._registry[name](main_config, adaptor_config, state)
# Creating an instance of the registryadaptor_registry = AdaptorRegistry()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copyright (c) 2023-2024, 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 torchfrom torch import nn
class ClsToken(nn.Module): def __init__(self, ndim: int, num_tokens: int = 1, enabled: bool = True, register_multiple: int = 0, ): super().__init__()
self.ndim = ndim self.enabled = enabled self.num_registers = 0 self.num_tokens = num_tokens if enabled: if register_multiple > 0: self.num_registers = register_multiple - (num_tokens % register_multiple)
scale = ndim ** -0.5 self.token = nn.Parameter(torch.randn(num_tokens + self.num_registers, ndim) * scale) else: self.token = None
self.num_patches = self.num_tokens + self.num_registers
def disable(self): self.token = None self.enabled = False
def forward(self, x: torch.Tensor): if self.token is None: return x
token = self.token.unsqueeze(0).expand(x.shape[0], -1, -1) x = torch.cat([ token, x, ], dim=1)
return x
def no_weight_decay(self): return [ 'token', ]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# 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 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.
from dataclasses import dataclassfrom typing import Optional
from .radio_model import Resolution
@dataclassclass RadioResource: url: str patch_size: int max_resolution: int preferred_resolution: Resolution vitdet_num_windowed: Optional[int] = None vitdet_num_global: Optional[int] = None
RESOURCE_MAP = { # RADIOv2.5 "radio_v2.5-b": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/radio-v2.5-b_half.pth.tar?download=true", patch_size=16, max_resolution=2048, preferred_resolution=(768, 768), vitdet_num_global=4, ), "radio_v2.5-l": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/radio-v2.5-l_half.pth.tar?download=true", patch_size=16, max_resolution=2048, preferred_resolution=(768, 768), vitdet_num_global=4, ), # RADIO "radio_v2.1": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.1_bf16.pth.tar?download=true", patch_size=16, max_resolution=2048, preferred_resolution=Resolution(432, 432), vitdet_num_windowed=5, ), "radio_v2": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.pth.tar?download=true", patch_size=16, max_resolution=2048, preferred_resolution=Resolution(432, 432), vitdet_num_windowed=5, ), "radio_v1": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v1.pth.tar?download=true", patch_size=14, max_resolution=1050, preferred_resolution=Resolution(378, 378), ), # E-RADIO "e-radio_v2": RadioResource( "https://huggingface.co/nvidia/RADIO/resolve/main/eradio_v2.pth.tar?download=true", patch_size=16, max_resolution=2048, preferred_resolution=Resolution(512, 512), ),}
DEFAULT_VERSION = "radio_v2.5-l"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221{ "adaptor_names": null, "architectures": [ "RADIOModel" ], "args": { "aa": null, "amp": true, "amp_dtype": "bfloat16", "amp_impl": "native", "aug_repeats": 0, "aug_splits": 0, "bn_eps": null, "bn_momentum": null, "cache_dir": null, "channels_last": false, "checkpoint_hist": 10, "chk_keep_forever": 50, "class_map": "", "clip_grad": null, "clip_mode": "norm", "cls_token_per_teacher": true, "coco_annotations_file": "/datasets/coco2017-adlsa/annotations/captions_val2017.json", "coco_image_dir": "/datasets/coco2017-adlsa/val2017", "color_jitter": 0.4, "cooldown_epochs": 0, "cpe_max_size": 2048, "crd_loss": false, "crd_loss_weight": 0.8, "crop_pct": null, "cutmix": 0.0, "cutmix_minmax": null, "dataset_download": false, "debug_full_knn": false, "decay_epochs": 90, "decay_milestones": [ 90, 180, 270 ], "decay_rate": 0.1, "device": "cuda:0", "dist_bn": "reduce", "dist_norm_weight": 0.0, "distributed": true, "drop": 0.0, "drop_block": null, "drop_connect": null, "drop_path": null, "dtype": "float32", "epoch_repeats": 0.0, "eval": false, "eval_metric": "knn_top1", "eval_teacher": false, "eval_teacher_only": false, "eval_throughput": false, "fast_norm": false, "fd_loss_fn": "MSE", "feature_normalization": "SHIP_NORM", "feature_summarizer": "cls_token", "feature_upscale_factor": null, "force_new_wandb_id": false, "force_spectral_reparam": true, "freeze_bn": false, "fsdp": false, "fuser": "", "gp": null, "grad_accum_steps": 1, "grad_checkpointing": false, "head_init_bias": null, "head_init_scale": null, "head_warmup": 5, "head_weight_decay": 5e-05, "hflip": 0.5, "img_size": null, "in_chans": null, "initial_checkpoint": "", "input_size": null, "interpolation": "", "layer_decay": null, "local_rank": 0, "log_interval": 50, "log_mlflow": false, "log_wandb": true, "loss_auto_balance": false, "lr_base": 0.1, "lr_base_scale": "", "lr_base_size": 256, "lr_cycle_decay": 0.5, "lr_cycle_limit": 1, "lr_cycle_mul": 1.0, "lr_k_decay": 1.0, "lr_noise": null, "lr_noise_pct": 0.67, "lr_noise_std": 1.0, "mean": null, "mesa": false, "min_lr": 0, "mixup": 0.0, "mixup_mode": "batch", "mixup_off_epoch": 0, "mixup_prob": 1.0, "mixup_switch_prob": 0.5, "mlp_hidden_size": 1520, "mlp_num_inner": 1, "mlp_version": "v2", "model": "vit_large_patch16_224", "model_kwargs": {}, "model_norm": false, "momentum": 0.9, "no_aug": false, "no_ddp_bb": true, "no_prefetcher": false, "no_resume_opt": false, "num_classes": null, "opt_betas": null, "opt_eps": null, "patience_epochs": 10, "pin_mem": false, "prefetcher": true, "pretrained": false, "rank": 0, "ratio": [ 0.75, 1.3333333333333333 ], "recount": 1, "recovery_interval": 0, "register_multiple": 8, "remode": "pixel", "reprob": 0.0, "reset_loss_state": true, "resplit": false, "save_images": false, "scale": [ 0.5, 1.0 ], "sched": "cosine", "seed": 42, "smoothing": 0.1, "spectral_reparam": false, "split_bn": false, "start_epoch": null, "std": null, "sync_bn": false, "synchronize_step": false, "teachers": [ { "fd_normalize": false, "feature_distillation": true, "input_size": 378, "model": "ViT-H-14-378-quickgelu", "name": "clip", "pretrained": "dfn5b", "type": "open_clip" }, { "fd_normalize": false, "feature_distillation": true, "input_size": 378, "model": "ViT-SO400M-14-SigLIP-384", "name": "siglip", "pretrained": "webli", "type": "open_clip", "use_summary": true }, { "fd_normalize": false, "feature_distillation": true, "input_size": 378, "model": "dinov2_vitg14_reg", "name": "dino_v2", "type": "dino_v2" }, { "fd_normalize": false, "feature_distillation": true, "input_size": 1024, "model": "vit-h", "name": "sam", "type": "sam", "use_summary": false } ], "torchcompile": null, "torchscript": false, "train_interpolation": "random", "train_split": "train", "tta": 0, "use_coco": false, "use_multi_epochs_loader": false, "val_ema_only": false, "val_split": "val", "vflip": 0.0, "vitdet_version": 1, "wandb_entity": "", "wandb_job_type": "", "wandb_name": "", "wandb_project": "", "warmup_lr": 1e-05, "warmup_prefix": false, "worker_seeding": "all", "workers": 8, "world_size": 128 }, "auto_map": { "AutoConfig": "hf_model.RADIOConfig", "AutoModel": "hf_model.RADIOModel" }, "max_resolution": 2048, "patch_size": 16, "preferred_resolution": [ 768, 768 ], "torch_dtype": "float32", "transformers_version": "4.40.1", "version": "radio_v2.5-l", "vitdet_window_size": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# Copyright (c) 2023-2024, 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.
from typing import List, Optional, Set, Tuple, Unionfrom types import MethodType
import torchfrom torch import nn
from timm.models import VisionTransformer, checkpoint_seq
from .vit_patch_generator import ViTPatchGenerator
def _forward_cpe(self: VisionTransformer, x: torch.Tensor) -> torch.Tensor: x = self.patch_generator(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) x = self.norm(x) return x
def _take_indices( num_blocks: int, n: Optional[Union[int, List[int], Tuple[int]]],) -> Tuple[Set[int], int]: if isinstance(n, int): assert n >= 0 take_indices = {x for x in range(num_blocks - n, num_blocks)} else: take_indices = {num_blocks + idx if idx < 0 else idx for idx in n} return take_indices, max(take_indices)
def _forward_intermediates_cpe( self, x: torch.Tensor, indices: Optional[Union[int, List[int], Tuple[int]]] = None, return_prefix_tokens: bool = False, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, aggregation: Optional[str] = "sparse",) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates.
The Dense layer aggregation method is inspired from the paper: "Dense Connector for MLLMs" by Yao, Huanjin et al. (2024). arXiv preprint arXiv:2405.13800}
Args: x: Input image tensor indices: Take last n blocks if int, select matching indices if sequence return_prefix_tokens: Return both prefix and spatial intermediate tokens norm: Apply norm layer to all intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features aggregation: intermediate layer aggregation method (sparse or dense) Returns: """ assert output_fmt in ('NCHW', 'NLC'), 'Output format must be one of NCHW or NLC.' assert aggregation in ('sparse', 'dense'), 'Aggregation must be one of sparse or dense.' reshape = output_fmt == 'NCHW' intermediates = [] take_indices, max_index = _take_indices(len(self.blocks), indices) # forward pass B, _, height, width = x.shape x = self.patch_generator(x)
if not stop_early: # can't slice blocks in torchscript blocks = self.blocks else: blocks = self.blocks[:max_index + 1]
accumulator = 0 num_accumulated = 0
for i, blk in enumerate(blocks): x = blk(x) if aggregation == "dense": accumulator = accumulator + x num_accumulated += 1 if i in take_indices: if aggregation == "dense": x_ = accumulator / num_accumulated num_accumulated = 0 accumulator = 0 else: x_ = x # normalize intermediates with final norm layer if enabled intermediates.append(self.norm(x_) if norm else x_)
# process intermediates
# split prefix (e.g. class, distill) and spatial feature tokens prefix_tokens = [y[:, 0:self.patch_generator.num_cls_tokens] for y in intermediates] intermediates = [y[:, self.patch_generator.num_skip:] for y in intermediates]
if reshape: # reshape to BCHW output format H = height // self.patch_generator.patch_size W = width // self.patch_generator.patch_size intermediates = [y.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() for y in intermediates] if not torch.jit.is_scripting() and return_prefix_tokens: # return_prefix not support in torchscript due to poor type handling intermediates = list(zip(intermediates, prefix_tokens)) if intermediates_only: return intermediates x = self.norm(x) return x, intermediates
def enable_cpe(model: nn.Module, max_img_size: Union[int, Tuple[int, int]] = 1024, num_cls_tokens: int = 1, pos_dropout: float = 0.1, register_multiple: int = 0,): if not isinstance(model, VisionTransformer): raise ValueError("CPE only support for VisionTransformer models!")
patch_size = model.patch_embed.patch_size[0] embed_dim = model.embed_dim input_dims = model.patch_embed.img_size normalize_patches = not isinstance(model.patch_embed.norm, nn.Identity) cls_token = model.cls_token is not None
max_img_size = int(round(max_img_size / patch_size) * patch_size)
patch_generator = ViTPatchGenerator( patch_size=patch_size, embed_dim=embed_dim, input_dims=input_dims, normalize_patches=normalize_patches, cls_token=cls_token, max_input_dims=max_img_size, pos_dropout=pos_dropout, num_cls_tokens=num_cls_tokens, register_multiple=register_multiple, )
model.patch_generator = patch_generator model.patch_embed = None model.cls_token = None model.pos_embed = None model.pos_drop = None model.num_cls_tokens = num_cls_tokens model.num_registers = patch_generator.num_registers
model.forward_features = MethodType(_forward_cpe, model) model.forward_intermediates = MethodType(_forward_intermediates_cpe, model)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227from logging import getLoggerimport mathimport osfrom typing import Union, Tuplefrom types import MethodType
import torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.nn.utils import parametrizefrom torch.nn.utils.parametrizations import _SpectralNorm
from timm.models.vision_transformer import Attention, Mlp
_EPS = 1e-5
class _SNReweight(_SpectralNorm): def __init__(self, weight: torch.Tensor, *args, init_norm_to_current: bool = False, alpha: float = 0.05, version: int = 2, **kwargs): super().__init__(weight, *args, **kwargs)
self.alpha = alpha self.version = version self.register_buffer('_sn_version', torch.tensor(version))
if init_norm_to_current: # This will set the numerator to match the denominator, which should preserve the original values init_scale = self._get_sigma(weight).item() else: init_scale = 1.0
if version == 1: init_value = init_scale elif version == 2: t = init_scale - alpha if t < _EPS: getLogger("spectral_reparam").warn(f'The initialized spectral norm {init_scale} is too small to be represented. Setting to {_EPS} instead.') t = _EPS
init_value = math.log(math.exp(t) - 1) else: raise ValueError(f'Unsupported version: {version}')
# Make 2D so that weight decay gets applied self.scale = nn.Parameter(torch.tensor([[init_value]], dtype=torch.float32, device=weight.device))
# Re-implementing this because we need to make division by sigma safe def _get_sigma(self, weight: torch.Tensor) -> torch.Tensor: if weight.ndim == 1: # Faster and more exact path, no need to approximate anything sigma = weight.norm() else: weight_mat = self._reshape_weight_to_matrix(weight) if self.training: self._power_method(weight_mat, self.n_power_iterations) # See above on why we need to clone u = self._u.clone(memory_format=torch.contiguous_format) v = self._v.clone(memory_format=torch.contiguous_format) # The proper way of computing this should be through F.bilinear, but # it seems to have some efficiency issues: # https://github.com/pytorch/pytorch/issues/58093 sigma = torch.dot(u, torch.mv(weight_mat, v))
return sigma + self.eps
def forward(self, weight: torch.Tensor, *args, **kwargs): dtype = weight.dtype sigma = self._get_sigma(weight, *args, **kwargs)
if self.version == 1: scale = self.scale elif self.version == 2: scale = F.softplus(self.scale) + self.alpha else: raise ValueError(f'Unsupported version: {self.version}')
scale = scale.float() / sigma.float()
y = weight * scale
if dtype in (torch.float16, torch.bfloat16): y = y.to(dtype) return y
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): version_key = f'{prefix}_sn_version' if version_key not in state_dict: self.version = 1 state_dict[version_key] = torch.tensor(1) return super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
class _AttnSNReweight(nn.Module): def __init__(self, weight: torch.Tensor, *args, init_norm_to_current: bool = False, renorm_values: bool = False, **kwargs): super().__init__()
parts = weight.split(weight.shape[0] // 3, dim=0)
ct = 2 if not renorm_values else 3
self.parts = nn.ModuleList([ _SNReweight(p, *args, init_norm_to_current=init_norm_to_current, **kwargs) if i < ct else nn.Identity() for i, p in enumerate(parts) ])
def forward(self, weight: torch.Tensor, *args, **kwargs): parts = weight.split(weight.shape[0] // 3, dim=0)
parts = [ fn(p) for fn, p in zip(self.parts, parts) ]
return torch.cat(parts, dim=0)
def enable_spectral_reparam(model: nn.Module, n_power_iterations: int = 1, eps: float = 1e-6, init_norm_to_current: bool = False, renorm_values: bool = True, renorm_mlp: bool = True): # print('Enabling spectral reparametrization') for mod in model.modules(): if isinstance(mod, Attention): parametrize.register_parametrization( mod.qkv, 'weight', _AttnSNReweight(mod.qkv.weight, n_power_iterations, dim=0, eps=eps, init_norm_to_current=init_norm_to_current, renorm_values=renorm_values), ) pass elif isinstance(mod, Mlp) and renorm_mlp: parametrize.register_parametrization( mod.fc1, 'weight', _SNReweight(mod.fc1.weight, n_power_iterations, dim=0, eps=eps, init_norm_to_current=init_norm_to_current), ) parametrize.register_parametrization( mod.fc2, 'weight', _SNReweight(mod.fc2.weight, n_power_iterations, dim=0, eps=eps, init_norm_to_current=init_norm_to_current), ) pass
def configure_spectral_reparam_from_args(model: nn.Module, args): spectral_reparam = getattr(args, 'spectral_reparam', False) if isinstance(spectral_reparam, bool) and spectral_reparam: enable_spectral_reparam(model, init_norm_to_current=args.pretrained) elif isinstance(spectral_reparam, dict): enable_spectral_reparam( model, n_power_iterations=spectral_reparam.get('n_power_iterations', 1), eps=spectral_reparam.get('eps', 1e-12), init_norm_to_current=args.pretrained, )
def disable_spectral_reparam(model: nn.Module): for mod in model.modules(): if isinstance(mod, Attention): parametrize.remove_parametrizations(mod.qkv, 'weight') pass elif isinstance(mod, Mlp): parametrize.remove_parametrizations(mod.fc1, 'weight') parametrize.remove_parametrizations(mod.fc2, 'weight') pass
if __name__ == '__main__': import argparse from . import radio_model as create_model
parser = argparse.ArgumentParser(description='Remove parametrization from state dict') parser.add_argument('--checkpoint', type=str, required=True, help='The checkpoint to load') parser.add_argument('--output', type=str, default='', help='Where to store the checkpoint') parser.add_argument('--release', default=False, action='store_true', help='Prune extraneous checkpoint fields') parser.add_argument('--strict', default=False, action='store_true', help='Strictly load the state dict')
args = parser.parse_args()
if not args.output: chk_dir, chk_name = os.path.split(args.checkpoint) args.output = os.path.join(chk_dir, f'clean_{chk_name}') print(f'Set output to "{args.output}"')
chk = torch.load(args.checkpoint, map_location='cpu', mmap=True)
model = create_model.create_model_from_args(chk['args'])
key = 'base_model.' mod_state = dict() extra_state = dict() for k, v in chk['state_dict'].items(): if k.startswith(key): mod_state[k[len(key):]] = v else: extra_state[k] = v
chk_load_info = model.load_state_dict(mod_state, strict=args.strict) if chk_load_info.unexpected_keys or chk_load_info.missing_keys: print(chk_load_info)
if chk['args'].spectral_reparam: disable_spectral_reparam(model)
if hasattr(chk['args'], 'dtype'): model.to(dtype=chk['args'].dtype)
mod_state = model.state_dict() final_state = dict() final_state.update({f'{key}{k}': v for k, v in mod_state.items()}) final_state.update(extra_state)
chk['state_dict'] = final_state chk['args'].spectral_reparam = False
if args.release: chk = { 'arch': chk['arch'], 'epoch': chk['epoch'], 'state_dict': chk['state_dict'], 'args': chk['args'], }
torch.save(chk, args.output) pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392#!/usr/bin/env python3
# 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 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.
# E-RADIO model from# Mike Ranzinger, Greg Heinrich, Jan Kautz, and Pavlo Molchanov. "AM-RADIO: Agglomerative Model--Reduce All Domains Into One." arXiv preprint arXiv:2312.06709 (2023).
# based on FasterViT, Swin Transformer, YOLOv8
# FasterViT:# Ali Hatamizadeh, Greg Heinrich, Hongxu Yin, Andrew Tao, Jose M. Alvarez, Jan Kautz, and Pavlo Molchanov. "FasterViT: Fast Vision Transformers with Hierarchical Attention." arXiv preprint arXiv:2306.06189 (2023).
import timmimport torchimport torch.nn as nnfrom timm.models.registry import register_model
from timm.models.layers import trunc_normal_, DropPath, LayerNorm2dimport numpy as npimport torch.nn.functional as Fimport mathimport warnings
######################### Codebase from YOLOv8## BEGINNING#######################
class C2f(nn.Module): """Faster Implementation of CSP Bottleneck with 2 convolutions.""" """From YOLOv8 codebase""" def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, drop_path=None): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__() if drop_path is None: drop_path = [0.0] * n
self.c = int(c2 * e) # hidden channels self.cv1 = Conv(c1, 2 * self.c, 1, 1) self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2) self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0, drop_path=drop_path[i]) for i in range(n))
def forward(self, x): """Forward pass through C2f layer.""" y = list(self.cv1(x).chunk(2, 1)) y.extend(m(y[-1]) for m in self.m) return self.cv2(torch.cat(y, 1))
def forward_split(self, x): """Forward pass using split() instead of chunk().""" y = list(self.cv1(x).split((self.c, self.c), 1)) y.extend(m(y[-1]) for m in self.m) return self.cv2(torch.cat(y, 1))
class Bottleneck(nn.Module): """Standard bottleneck."""
def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5, drop_path=0.0): # ch_in, ch_out, shortcut, groups, kernels, expand super().__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, k[0], 1) self.cv2 = Conv(c_, c2, k[1], 1, g=g) self.add = shortcut and c1 == c2 self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
def forward(self, x): """'forward()' applies the YOLOv5 FPN to input data.""" return x + self.drop_path1(self.cv2(self.cv1(x))) if self.add else self.cv2(self.cv1(x))
class Conv(nn.Module): """Modified to support layer fusion""" default_act = nn.SiLU() # default activation
def __init__(self, a, b, kernel_size=1, stride=1, padding=None, g=1, dilation=1, bn_weight_init=1, bias=False, act=True): super().__init__()
self.conv = torch.nn.Conv2d(a, b, kernel_size, stride, autopad(kernel_size, padding, dilation), dilation, g, bias=False) if 1: self.bn = torch.nn.BatchNorm2d(b) torch.nn.init.constant_(self.bn.weight, bn_weight_init) torch.nn.init.constant_(self.bn.bias, 0) self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
def forward(self,x): x = self.conv(x) x = self.bn(x) x = self.act(x) return x
@torch.no_grad() def switch_to_deploy(self): # return 1 if not isinstance(self.bn, nn.Identity): c, bn = self.conv, self.bn w = bn.weight / (bn.running_var + bn.eps) ** 0.5 w = c.weight * w[:, None, None, None] b = bn.bias - bn.running_mean * bn.weight / \ (bn.running_var + bn.eps)**0.5
self.conv.weight.data.copy_(w) self.conv.bias = nn.Parameter(b)
self.bn = nn.Identity()
def autopad(k, p=None, d=1): # kernel, padding, dilation """Pad to 'same' shape outputs.""" if d > 1: k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size if p is None: p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad return p
######################### Codebase from YOLOv8## END#######################
def pixel_unshuffle(data, factor=2): # performs nn.PixelShuffle(factor) in reverse, torch has some bug for ONNX and TRT, so doing it manually B, C, H, W = data.shape return data.view(B, C, factor, H//factor, factor, W//factor).permute(0,1,2,4,3,5).reshape(B, -1, H//factor, W//factor)
class SwiGLU(nn.Module): # should be more advanced, but doesnt improve results so far def forward(self, x): x, gate = x.chunk(2, dim=-1) return F.silu(gate) * x
def window_partition(x, window_size): """ Function for partitioning image into windows and later do windowed attention Args: x: (B, C, H, W) window_size: window size Returns: windows - local window features (num_windows*B, window_size*window_size, C) (Hp, Wp) - the size of the padded image """ B, C, H, W = x.shape
if window_size == 0 or (window_size==H and window_size==W): windows = x.flatten(2).transpose(1, 2) Hp, Wp = H, W else: pad_h = (window_size - H % window_size) % window_size pad_w = (window_size - W % window_size) % window_size if pad_h > 0 or pad_w > 0: x = F.pad(x, (0, pad_w, 0, pad_h), mode="reflect") Hp, Wp = H + pad_h, W + pad_w
x = x.view(B, C, Hp // window_size, window_size, Wp // window_size, window_size) windows = x.permute(0, 2, 4, 3, 5, 1).reshape(-1, window_size*window_size, C)
return windows, (Hp, Wp)
class Conv2d_BN(nn.Module): ''' Conv2d + BN layer with folding capability to speed up inference Can be merged with Conv() function with additional arguments ''' def __init__(self, a, b, kernel_size=1, stride=1, padding=0, dilation=1, groups=1, bn_weight_init=1, bias=False): super().__init__() self.conv = torch.nn.Conv2d(a, b, kernel_size, stride, padding, dilation, groups, bias=False) if 1: self.bn = torch.nn.BatchNorm2d(b) torch.nn.init.constant_(self.bn.weight, bn_weight_init) torch.nn.init.constant_(self.bn.bias, 0)
def forward(self,x): x = self.conv(x) x = self.bn(x) return x
@torch.no_grad() def switch_to_deploy(self): if not isinstance(self.bn, nn.Identity): c, bn = self.conv, self.bn w = bn.weight / (bn.running_var + bn.eps) ** 0.5 w = c.weight * w[:, None, None, None] b = bn.bias - bn.running_mean * bn.weight / \ (bn.running_var + bn.eps)**0.5 self.conv.weight.data.copy_(w) self.conv.bias = nn.Parameter(b) self.bn = nn.Identity()
def window_reverse(windows, window_size, H, W, pad_hw): """ Windows to the full feature map Args: windows: local window features (num_windows*B, window_size, window_size, C) window_size: Window size H: Height of image W: Width of image pad_w - a tuple of image passing used in windowing step Returns: x: (B, C, H, W)
""" # print(f"window_reverse, windows.shape {windows.shape}") Hp, Wp = pad_hw if window_size == 0 or (window_size==H and window_size==W): B = int(windows.shape[0] / (Hp * Wp / window_size / window_size)) x = windows.transpose(1, 2).view(B, -1, H, W) else: B = int(windows.shape[0] / (Hp * Wp / window_size / window_size)) x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) x = x.permute(0, 5, 1, 3, 2, 4).reshape(B,windows.shape[2], Hp, Wp)
if Hp > H or Wp > W: x = x[:, :, :H, :W, ].contiguous()
return x
class PosEmbMLPSwinv2D(nn.Module): """ 2D positional embedding from Swin Transformer v2 Added functionality to store the positional embedding in the model and not recompute it every time """ def __init__( self, window_size, pretrained_window_size, num_heads, seq_length, no_log=False, cpb_mlp_hidden=512, ): super().__init__() self.window_size = window_size self.num_heads = num_heads # mlp to generate continuous relative position bias self.cpb_mlp = nn.Sequential( nn.Linear(2, cpb_mlp_hidden, bias=True), nn.ReLU(inplace=True), nn.Linear(cpb_mlp_hidden, num_heads, bias=False), )
self.grid_exists = False self.seq_length = seq_length self.deploy = False self.num_heads = num_heads self.no_log = no_log self.pretrained_window_size = pretrained_window_size self.relative_bias_window_size = window_size
relative_coords_table, relative_position_index, relative_bias = self.relative_bias_initialization(window_size, num_heads, pretrained_window_size, seq_length, no_log)
self.register_buffer("relative_coords_table", relative_coords_table) self.register_buffer("relative_position_index", relative_position_index) self.register_buffer("relative_bias", relative_bias) # for EMA
def relative_bias_initialization(self, window_size, num_heads, pretrained_window_size, seq_length, no_log): # as in separate function to support window size chage after model weights loading relative_coords_h = torch.arange( -(window_size[0] - 1), window_size[0], dtype=torch.float32 ) relative_coords_w = torch.arange( -(window_size[1] - 1), window_size[1], dtype=torch.float32 ) relative_coords_table = ( torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w])) .permute(1, 2, 0) .contiguous() .unsqueeze(0) ) # 1, 2*Wh-1, 2*Ww-1, 2 if pretrained_window_size[0] > 0: relative_coords_table[:, :, :, 0] /= pretrained_window_size[0] - 1 relative_coords_table[:, :, :, 1] /= pretrained_window_size[1] - 1 else: relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1 relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1
if not no_log: relative_coords_table *= 8 # normalize to -8, 8 relative_coords_table = ( torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / np.log2(8) )
# get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = ( coords_flatten[:, :, None] - coords_flatten[:, None, :] ) # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute( 1, 2, 0 ).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
relative_bias = torch.zeros(1, num_heads, seq_length, seq_length)
self.relative_bias_window_size = window_size
return relative_coords_table, relative_position_index, relative_bias
def switch_to_deploy(self): self.deploy = True self.grid_exists = True
def forward(self, input_tensor): # for efficiency, we want this forward to be folded into a single operation (sum) # if resolution stays the same, then we dont need to recompute MLP layers
if not self.deploy or self.training: self.grid_exists = False
#compare if all elements in self.window_size list match those in self.relative_bias_window_size if not all([self.window_size[i] == self.relative_bias_window_size[i] for i in range(len(self.window_size))]): relative_coords_table, relative_position_index, relative_bias = self.relative_bias_initialization(self.window_size, self.num_heads, self.pretrained_window_size, self.seq_length, self.no_log)
self.relative_coords_table = relative_coords_table.to(self.relative_coords_table.device) self.relative_position_index = relative_position_index.to(self.relative_position_index.device) self.relative_bias = relative_bias.to(self.relative_bias.device)
if self.deploy and self.grid_exists: input_tensor = input_tensor + self.relative_bias return input_tensor
if 1: self.grid_exists = True
relative_position_bias_table = self.cpb_mlp( self.relative_coords_table ).view(-1, self.num_heads) relative_position_bias = relative_position_bias_table[ self.relative_position_index.view(-1) ].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1, ) # Wh*Ww,Wh*Ww,nH
relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() # nH, Wh*Ww, Wh*Ww relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
self.relative_bias = relative_position_bias.unsqueeze(0)
input_tensor = input_tensor + self.relative_bias return input_tensor
class GRAAttentionBlock(nn.Module): def __init__(self, window_size, dim_in, dim_out, num_heads, drop_path=0., qk_scale=None, qkv_bias=False, norm_layer=nn.LayerNorm, layer_scale=None, use_swiglu=True, subsample_ratio=1, dim_ratio=1, conv_base=False, do_windowing=True, multi_query=False, use_shift=0, cpb_mlp_hidden=512, conv_groups_ratio=0): ''' Global Resolution Attention Block , see README for details Attention with subsampling to get a bigger receptive field for attention conv_base - use conv2d instead of avgpool2d for downsample / upsample
''' super().__init__()
self.shift_size=window_size//2 if use_shift else 0
self.do_windowing = do_windowing self.subsample_ratio = subsample_ratio
if do_windowing: if conv_base: self.downsample_op = nn.Conv2d(dim_in, dim_out, kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity()
self.downsample_mixer = nn.Identity() self.upsample_mixer = nn.Identity() self.upsample_op = nn.ConvTranspose2d(dim_in, dim_out, kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity() else: self.downsample_op = nn.AvgPool2d(kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity() self.downsample_mixer = Conv2d_BN(dim_in, dim_out, kernel_size=1, stride=1) if subsample_ratio > 1 else nn.Identity() self.upsample_mixer = nn.Upsample(scale_factor=subsample_ratio, mode='nearest') if subsample_ratio > 1 else nn.Identity() self.upsample_op = Conv2d_BN(dim_in, dim_out, kernel_size=1, stride=1, padding=0, bias=False) if subsample_ratio > 1 else nn.Identity()
# in case there is no downsampling conv we want to have it separately # will help with information propagation between windows if subsample_ratio == 1: # conv_groups_ratio=0 self.pre_conv = Conv2d_BN(dim_in, dim_in, kernel_size=3, stride=1, padding=1, groups=max(1,int(conv_groups_ratio*dim_in)), bias=False) # self.pre_conv = nn.Conv2d(dim_in, dim_in, kernel_size=3, stride=1, padding=1, groups=max(1,int(conv_groups_ratio*dim_in)), bias=False) # self.pre_conv_act = nn.ReLU6() #for simplicity: self.pre_conv_act = nn.Identity() if conv_groups_ratio == -1: self.pre_conv = nn.Identity() self.pre_conv_act = nn.Identity()
self.window_size = window_size
self.norm1 = norm_layer(dim_in)
self.attn = WindowAttention( dim_in, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, resolution=window_size, seq_length=window_size**2, dim_out=dim_in, multi_query=multi_query, shift_size=self.shift_size, cpb_mlp_hidden=cpb_mlp_hidden)
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
use_layer_scale = layer_scale is not None and type(layer_scale) in [int, float] self.gamma1 = nn.Parameter(layer_scale * torch.ones(dim_in)) if use_layer_scale else 1
### mlp layer mlp_ratio = 4 self.norm2 = norm_layer(dim_in) mlp_hidden_dim = int(dim_in * mlp_ratio)
activation = nn.GELU if not use_swiglu else SwiGLU mlp_hidden_dim = int((4 * dim_in * 1 / 2) / 64) * 64 if use_swiglu else mlp_hidden_dim
self.mlp = Mlp(in_features=dim_in, hidden_features=mlp_hidden_dim, act_layer=activation, use_swiglu=use_swiglu)
self.gamma2 = nn.Parameter(layer_scale * torch.ones(dim_in)) if layer_scale else 1 self.drop_path2=DropPath(drop_path) if drop_path > 0. else nn.Identity()
def forward(self, x): skip_connection = x attn_mask = None
# in case there is no downsampling conv we want to have it separately # will help with information propagation if self.subsample_ratio == 1: x = self.pre_conv_act(self.pre_conv(x)) + skip_connection
if self.do_windowing: # performing windowing if required x = self.downsample_op(x) x = self.downsample_mixer(x)
if self.window_size>0: H, W = x.shape[2], x.shape[3]
if self.shift_size > 0 and H>self.window_size and W>self.window_size: # @swin like cyclic shift, doesnt show better performance x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(2, 3))
x, pad_hw = window_partition(x, self.window_size)
if self.shift_size > 0 and H>self.window_size and W>self.window_size: # set atten matrix to have -100 and the top right square # attn[:, :, :-self.shift_size, -self.shift_size:] = -100.0 # calculate attention mask for SW-MSA # not used in final version, can be useful for some cases especially for high res H, W = pad_hw img_mask = torch.zeros((1, H, W, 1), device=x.device) # 1 H W 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 img_mask = img_mask.transpose(1,2).transpose(1,3) mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
mask_windows = mask_windows[0].view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
# window attention x = x + self.drop_path1(self.gamma1*self.attn(self.norm1(x), attn_mask=attn_mask)) # or pass H,W # mlp layer x = x + self.drop_path2(self.gamma2*self.mlp(self.norm2(x)))
if self.do_windowing: if self.window_size > 0: x = window_reverse(x, self.window_size, H, W, pad_hw)
# reverse cyclic shift if self.shift_size > 0 and H>self.window_size and W>self.window_size: # @swin like cyclic shift, not tested x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(2, 3))
x = self.upsample_mixer(x) x = self.upsample_op(x)
if x.shape[2] != skip_connection.shape[2] or x.shape[3] != skip_connection.shape[3]: x = torch.nn.functional.pad(x, ( 0, -x.shape[3] + skip_connection.shape[3], 0, -x.shape[2] + skip_connection.shape[2]), mode="reflect") # need to add skip connection because downsampling and upsampling will break residual connection # 0.5 is needed to make sure that the skip connection is not too strong # in case of no downsample / upsample we can show that 0.5 compensates for the residual connection x = 0.5 * x + 0.5 * skip_connection return x
class MultiResolutionAttention(nn.Module): """ MultiResolutionAttention (MRA) module The idea is to use multiple attention blocks with different resolution Feature maps are downsampled / upsampled for each attention block on different blocks Every attention block supports windowing """
def __init__(self, window_size, sr_ratio, dim, dim_ratio, num_heads, do_windowing=True, layer_scale=1e-5, norm_layer=nn.LayerNorm, drop_path = 0, qkv_bias=False, qk_scale=1.0, use_swiglu=True, multi_query=False, conv_base=False, use_shift=0, cpb_mlp_hidden=512, conv_groups_ratio=0) -> None: """ Args: input_resolution: input image resolution window_size: window size compression_ratio: compression ratio max_depth: maximum depth of the GRA module use_shift: do window shifting """ super().__init__()
depth = len(sr_ratio)
self.attention_blocks = nn.ModuleList()
for i in range(depth): subsample_ratio = sr_ratio[i] if len(window_size) > i: window_size_local = window_size[i] else: window_size_local = window_size[0]
self.attention_blocks.append(GRAAttentionBlock(window_size=window_size_local, dim_in=dim, dim_out=dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, norm_layer=norm_layer, layer_scale=layer_scale, drop_path=drop_path, use_swiglu=use_swiglu, subsample_ratio=subsample_ratio, dim_ratio=dim_ratio, do_windowing=do_windowing, multi_query=multi_query, conv_base=conv_base, use_shift=use_shift, cpb_mlp_hidden=cpb_mlp_hidden, conv_groups_ratio=conv_groups_ratio), )
def forward(self, x):
for attention_block in self.attention_blocks: x = attention_block(x)
return x
class Mlp(nn.Module): """ Multi-Layer Perceptron (MLP) block """
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, use_swiglu=True, drop=0.): """ Args: in_features: input features dimension. hidden_features: hidden features dimension. out_features: output features dimension. act_layer: activation function. drop: dropout rate. """
super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features * (2 if use_swiglu else 1), bias=False) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features, bias=False)
def forward(self, x): x_size = x.size() x = x.view(-1, x_size[-1]) x = self.fc1(x) x = self.act(x) x = self.fc2(x) x = x.view(x_size) return x
class Downsample(nn.Module): """ Down-sampling block Pixel Unshuffle is used for down-sampling, works great accuracy - wise but takes 10% more TRT time """
def __init__(self, dim, shuffle = False, ): """ Args: dim: feature size dimension. shuffle: idea with keep_dim: bool argument for maintaining the resolution. """
super().__init__() dim_out = 2 * dim
if shuffle: self.norm = lambda x: pixel_unshuffle(x, factor=2) self.reduction = Conv2d_BN(dim*4, dim_out, 1, 1, 0, bias=False) # pixel unshuffleging works well but doesnt provide any speedup else: # removed layer norm for better, in this formulation we are getting 10% better speed # LayerNorm for high resolution inputs will be a pain as it pools over the entire spatial dimension # therefore we remove it compared to the original implementation in FasterViT self.norm = nn.Identity() self.reduction = Conv2d_BN(dim, dim_out, 3, 2, 1, bias=False)
def forward(self, x): x = self.norm(x) x = self.reduction(x) return x
class PatchEmbed(nn.Module): """ Patch embedding block Used to convert image into an initial set of feature maps with lower resolution """
def __init__(self, in_chans=3, in_dim=64, dim=96, shuffle_down=False): """ Args: in_chans: number of input channels. in_dim: intermediate feature size dimension to speed up stem. dim: final stem channel number shuffle_down: use PixelUnshuffle for down-sampling, effectively increases the receptive field """
super().__init__() # shuffle_down = False if not shuffle_down: self.proj = nn.Identity() self.conv_down = nn.Sequential( Conv2d_BN(in_chans, in_dim, 3, 2, 1, bias=False), nn.ReLU(), Conv2d_BN(in_dim, dim, 3, 2, 1, bias=False), nn.ReLU() ) else: self.proj = lambda x: pixel_unshuffle(x, factor=4) self.conv_down = nn.Sequential(Conv2d_BN(in_chans*16, dim, 3, 1, 1), nn.ReLU(), )
def forward(self, x): x = self.proj(x) x = self.conv_down(x) return x
class ConvBlock(nn.Module): """ Convolutional block, used in first couple of stages Experimented with plan resnet-18 like modules, they are the best in terms of throughput Finally, YOLOv8 idea seem to work fine (resnet-18 like block with squeezed feature dimension, and feature concatendation at the end) """ def __init__(self, dim, drop_path=0., layer_scale=None, kernel_size=3, ): super().__init__()
self.conv1 = Conv2d_BN(dim, dim, kernel_size=kernel_size, stride=1, padding=1) self.act1 = nn.GELU()
self.conv2 = Conv2d_BN(dim, dim, kernel_size=kernel_size, stride=1, padding=1)
self.layer_scale = layer_scale if layer_scale is not None and type(layer_scale) in [int, float]: self.gamma = nn.Parameter(layer_scale * torch.ones(dim)) self.layer_scale = True else: self.layer_scale = False self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
def forward(self, x): input = x
x = self.conv1(x) x = self.act1(x) x = self.conv2(x)
if self.layer_scale: x = x * self.gamma.view(1, -1, 1, 1) x = input + self.drop_path(x) return x
class WindowAttention(nn.Module): # Windowed Attention from SwinV2 # use a MLP trick to deal with various input image resolutions, then fold it to improve speed
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, resolution=0, seq_length=0, dim_out=None, multi_query=False, shift_size=0, cpb_mlp_hidden=512): # taken from EdgeViT and tweaked with attention bias. super().__init__() if not dim_out: dim_out = dim self.shift_size = shift_size self.multi_query = multi_query self.num_heads = num_heads head_dim = dim // num_heads self.head_dim = dim // num_heads
self.dim_internal = dim
self.scale = qk_scale or head_dim ** -0.5 if not multi_query: self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) else: self.qkv = nn.Linear(dim, dim + 2*self.head_dim, bias=qkv_bias)
self.proj = nn.Linear(dim, dim_out, bias=False) # attention positional bias self.pos_emb_funct = PosEmbMLPSwinv2D(window_size=[resolution, resolution], pretrained_window_size=[resolution, resolution], num_heads=num_heads, seq_length=seq_length, cpb_mlp_hidden=cpb_mlp_hidden)
self.resolution = resolution
def forward(self, x, attn_mask = None): B, N, C = x.shape
if not self.multi_query: qkv = self.qkv(x).reshape(B, -1, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] else: qkv = self.qkv(x) (q, k, v) = qkv.split([self.dim_internal, self.head_dim, self.head_dim], dim=2)
q = q.reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) k = k.reshape(B, -1, 1, C // self.num_heads).permute(0, 2, 1, 3) v = v.reshape(B, -1, 1, C // self.num_heads).permute(0, 2, 1, 3)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = self.pos_emb_funct(attn)
#add window shift if attn_mask is not None: nW = attn_mask.shape[0] attn = attn.view(B // nW, nW, self.num_heads, N, N) + attn_mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N)
attn = attn.softmax(dim=-1) x = (attn @ v).transpose(1, 2).reshape(B, -1, C) x = self.proj(x) return x
class ERADIOLayer(nn.Module): """ E-RADIO Layer """
def __init__(self, dim, depth, num_heads, window_size, conv=False, downsample=True, mlp_ratio=4., qkv_bias=False, qk_scale=None, norm_layer=nn.LayerNorm, drop_path=0., layer_scale=None, layer_scale_conv=None, sr_dim_ratio=1, sr_ratio=1, multi_query=False, use_swiglu=True, yolo_arch=False, downsample_shuffle=False, conv_base=False, use_shift=False, cpb_mlp_hidden=512, conv_groups_ratio=0, verbose: bool = True,
): """ Args: dim: feature size dimension. depth: number of layers in each stage. input_resolution: input image resolution. window_size: window size in each stage. downsample: bool argument for down-sampling. mlp_ratio: MLP ratio. num_heads: number of heads in each stage. qkv_bias: bool argument for query, key, value learnable bias. qk_scale: bool argument to scaling query, key. drop: dropout rate. attn_drop: attention dropout rate. drop_path: drop path rate. norm_layer: normalization layer. layer_scale: layer scaling coefficient. use_shift: SWIN like window shifting for half the window size for every alternating layer (considering multi-resolution) conv_groups_ratio: group ratio for conv when no subsampling in multi-res attention """
super().__init__() self.conv = conv self.yolo_arch=False self.verbose = verbose if conv: if not yolo_arch: self.blocks = nn.ModuleList([ ConvBlock(dim=dim, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, layer_scale=layer_scale_conv) for i in range(depth)]) self.blocks = nn.Sequential(*self.blocks) else: self.blocks = C2f(dim,dim,n=depth,shortcut=True,e=0.5) self.yolo_arch=True else: if not isinstance(window_size, list): window_size = [window_size] self.window_size = window_size[0] self.do_single_windowing = True if not isinstance(sr_ratio, list): sr_ratio = [sr_ratio] self.sr_ratio = sr_ratio if any([sr!=1 for sr in sr_ratio]) or len(set(window_size))>1: self.do_single_windowing = False do_windowing = True else: self.do_single_windowing = True do_windowing = False
#for v2_2 if conv_groups_ratio != -1: self.do_single_windowing = False do_windowing = True
self.blocks = nn.ModuleList() for i in range(depth): self.blocks.append( MultiResolutionAttention(window_size=window_size, sr_ratio=sr_ratio, dim=dim, dim_ratio = sr_dim_ratio, num_heads=num_heads, norm_layer=norm_layer, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, layer_scale=layer_scale, qkv_bias=qkv_bias, qk_scale=qk_scale, use_swiglu=use_swiglu, do_windowing=do_windowing, multi_query=multi_query, conv_base=conv_base, cpb_mlp_hidden=cpb_mlp_hidden, use_shift =0 if ((not use_shift) or ((i) % 2 == 0)) else True , conv_groups_ratio=conv_groups_ratio, )) self.blocks = nn.Sequential(*self.blocks)
self.transformer = not conv self.downsample = None if not downsample else Downsample(dim=dim, shuffle=downsample_shuffle)
def forward(self, x): B, C, H, W = x.shape
# do padding for transforemr interpolate = True if self.transformer and interpolate: # Windowed Attention will split feature map into windows with the size of window_size x window_size # if the resolution is not divisible by window_size, we need to interpolate the feature map # can be done via padding, but doing so after training hurts the model performance. # interpolation affects the performance as well, but not as much as padding if isinstance(self.window_size, list) or isinstance(self.window_size, tuple): current_max_window_size = max(self.window_size) else: current_max_window_size = self.window_size
max_window_size = max([res_upsample*current_max_window_size for res_upsample in self.sr_ratio]) if H % max_window_size != 0 or W % max_window_size != 0: new_h = int(np.ceil(H/max_window_size)*max_window_size) new_w = int(np.ceil(W/max_window_size)*max_window_size) x = F.interpolate(x, size=(new_h, new_w), mode='nearest') if self.verbose: warnings.warn(f"Choosen window size is not optimal for given resolution. Interpolation of features maps will be done and it can affect the performance. Max window size is {max_window_size}, feature map size is {H}x{W}, interpolated feature map size is {new_h}x{new_w}.")
if self.transformer and self.do_single_windowing: H, W = x.shape[2], x.shape[3] x, pad_hw = window_partition(x, self.window_size)
#run main blocks x = self.blocks(x)
if self.transformer and self.do_single_windowing: x = window_reverse(x, self.window_size, H, W, pad_hw)
if self.transformer and interpolate: #lets keep original resolution, might be not ideal, but for the upsampling tower we need to keep the expected resolution. x = F.interpolate(x, size=(H, W), mode='nearest')
if self.downsample is None: return x, x
return self.downsample(x), x # changing to output pre downsampled features
class InterpolateLayer(nn.Module): def __init__(self, size=None, scale_factor=None, mode='nearest'): super(InterpolateLayer, self).__init__() self.size = size self.scale_factor = scale_factor self.mode = mode
def forward(self, x): return F.interpolate(x, size=self.size, scale_factor=self.scale_factor, mode=self.mode)
class HiResNeck(nn.Module): """ The block is used to output dense features from all stages Otherwise, by default, only the last stage features are returned with E-RADIO """ def __init__(self, dim, depths, neck_start_stage, full_features_head_dim, downsample_enabled):
''' Hi Resolution neck to support output of high res features that are useful for dense tasks. depths - total number of layers in the base model neck_start_stage - when to start the neck, 0 - start from the first stage, 1 - start from the second stage etc. earlier layers result in higher resolution features at the cost of compute full_features_head_dim - number of channels in the dense features head ''' super().__init__() # create feature projection layers for segmentation output self.neck_features_proj = nn.ModuleList() self.neck_start_stage = neck_start_stage upsample_ratio = 1 for i in range(len(depths)): level_n_features_output = int(dim * 2 ** i)
if self.neck_start_stage > i: continue
if (upsample_ratio > 1) or full_features_head_dim!=level_n_features_output: feature_projection = nn.Sequential() if False: feature_projection.add_module("norm",nn.BatchNorm2d(level_n_features_output)) #fast, but worse feature_projection.add_module("dconv", nn.ConvTranspose2d(level_n_features_output, full_features_head_dim, kernel_size=upsample_ratio, stride=upsample_ratio)) else: # B, in_channels, H, W -> B, in_channels, H*upsample_ratio, W*upsample_ratio # print("upsample ratio", upsample_ratio, level_n_features_output, level_n_features_output) feature_projection.add_module("upsample", InterpolateLayer(scale_factor=upsample_ratio, mode='nearest')) feature_projection.add_module("conv1", nn.Conv2d(level_n_features_output, level_n_features_output, kernel_size=3, stride=1, padding=1, groups=level_n_features_output)) feature_projection.add_module("norm",nn.BatchNorm2d(level_n_features_output)) # B, in_channels, H*upsample_ratio, W*upsample_ratio -> B, full_features_head_dim, H*upsample_ratio, W*upsample_ratio feature_projection.add_module("conv2", nn.Conv2d(level_n_features_output, full_features_head_dim, kernel_size=1, stride=1, padding=0)) else: feature_projection = nn.Sequential()
self.neck_features_proj.append(feature_projection)
if i>0 and downsample_enabled[i]: upsample_ratio *= 2
def forward(self, x, il_level=-1, full_features=None): if self.neck_start_stage > il_level: return full_features
if full_features is None: full_features = self.neck_features_proj[il_level - self.neck_start_stage](x) else: #upsample torch tensor x to match full_features size, and add to full_features feature_projection = self.neck_features_proj[il_level - self.neck_start_stage](x) if feature_projection.shape[2] != full_features.shape[2] or feature_projection.shape[3] != full_features.shape[3]: feature_projection = torch.nn.functional.pad(feature_projection, ( 0, -feature_projection.shape[3] + full_features.shape[3], 0, -feature_projection.shape[2] + full_features.shape[2])) full_features = full_features + feature_projection return full_features
class ERADIO(nn.Module): """ Efficient RADIO """
def __init__(self, dim, in_dim, depths, window_size, mlp_ratio, num_heads, drop_path_rate=0.2, in_chans=3, num_classes=1000, qkv_bias=False, qk_scale=None, layer_scale=None, layer_scale_conv=None, layer_norm_last=False, sr_ratio = [1, 1, 1, 1], max_depth = -1, conv_base=False, use_swiglu=False, multi_query=False, norm_layer=nn.LayerNorm, drop_uniform=False, yolo_arch=False, shuffle_down=False, downsample_shuffle=False, return_full_features=False, full_features_head_dim=128, neck_start_stage=1, use_neck=False, use_shift=False, cpb_mlp_hidden=512, conv_groups_ratio=0, verbose: bool = False, **kwargs): """ Args: dim: feature size dimension. depths: number of layers in each stage. window_size: window size in each stage. mlp_ratio: MLP ratio. num_heads: number of heads in each stage. drop_path_rate: drop path rate. in_chans: number of input channels. num_classes: number of classes. qkv_bias: bool argument for query, key, value learnable bias. qk_scale: bool argument to scaling query, key. drop_rate: dropout rate. attn_drop_rate: attention dropout rate. norm_layer: normalization layer. layer_scale: layer scaling coefficient. return_full_features: output dense features as well as logits full_features_head_dim: number of channels in the dense features head neck_start_stage: a stage id to start full feature neck. Model has 4 stages, indix starts with 0 for 224 resolution, the output of the stage before downsample: stage 0: 56x56, stage 1: 28x28, stage 2: 14x14, stage 3: 7x7 use_neck: even for summarization embedding use neck use_shift: SWIN like window shifting but without masking attention conv_groups_ratio: will be used for conv blocks where there is no multires attention, if 0 then normal conv, if 1 then channels are independent, if -1 then no conv at all
""" super().__init__()
num_features = int(dim * 2 ** (len(depths) - 1)) self.num_classes = num_classes self.patch_embed = PatchEmbed(in_chans=in_chans, in_dim=in_dim, dim=dim, shuffle_down=shuffle_down) # set return_full_features true if we want to return full features from all stages self.return_full_features = return_full_features self.use_neck = use_neck
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] if drop_uniform: dpr = [drop_path_rate for x in range(sum(depths))]
if not isinstance(max_depth, list): max_depth = [max_depth] * len(depths)
self.levels = nn.ModuleList() for i in range(len(depths)): conv = True if (i == 0 or i == 1) else False
level = ERADIOLayer(dim=int(dim * 2 ** i), depth=depths[i], num_heads=num_heads[i], window_size=window_size[i], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, conv=conv, drop_path=dpr[sum(depths[:i]):sum(depths[:i + 1])], downsample=(i < len(depths) - 1), layer_scale=layer_scale, layer_scale_conv=layer_scale_conv, sr_ratio=sr_ratio[i], use_swiglu=use_swiglu, multi_query=multi_query, norm_layer=norm_layer, yolo_arch=yolo_arch, downsample_shuffle=downsample_shuffle, conv_base=conv_base, cpb_mlp_hidden=cpb_mlp_hidden, use_shift=use_shift, conv_groups_ratio=conv_groups_ratio, verbose=verbose)
self.levels.append(level)
if self.return_full_features or self.use_neck: #num_heads downsample_enabled = [self.levels[i-1].downsample is not None for i in range(len(self.levels))] self.high_res_neck = HiResNeck(dim, depths, neck_start_stage, full_features_head_dim, downsample_enabled)
self.switched_to_deploy = False
self.norm = LayerNorm2d(num_features) if layer_norm_last else nn.BatchNorm2d(num_features) self.avgpool = nn.AdaptiveAvgPool2d(1) self.head = nn.Linear(num_features, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, LayerNorm2d): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.BatchNorm2d): nn.init.ones_(m.weight) nn.init.zeros_(m.bias)
@torch.jit.ignore def no_weight_decay_keywords(self): return {'rpb'}
def forward_features(self, x): _, _, H, W = x.shape if H % 32 != 0 or W % 32 != 0: raise ValueError(f"E-RADIO requires input dimensions to be divisible by 32 but got H x W: {H} x {W}") x = self.patch_embed(x) full_features = None for il, level in enumerate(self.levels): x, pre_downsample_x = level(x)
if self.return_full_features or self.use_neck: full_features = self.high_res_neck(pre_downsample_x, il, full_features)
# x = self.norm(full_features if (self.return_full_features or self.use_neck) else x) x = self.norm(x) # new version for
if not self.return_full_features: return x, None
return x, full_features
def forward(self, x): x, full_features = self.forward_features(x)
x = self.avgpool(x) x = torch.flatten(x, 1)
x = self.head(x) if full_features is not None: return x, full_features return x
def switch_to_deploy(self): ''' A method to perform model self-compression merges BN into conv layers converts MLP relative positional bias into precomputed buffers ''' if not self.switched_to_deploy: for level in [self.patch_embed, self.levels, self.head]: for module in level.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() self.switched_to_deploy = True
def change_window_size(self, new_window_size): """ E-RADIO employs windowed attention, which may be sensitive to the choice of this parameter, especially in cases of uneven partitioning of the feature maps. E-RADIO allows for the adjustment of the window size after training, making it adaptable to different input image resolutions. The recommended values for window size based on input resolution are as follows:
Input Resolution | Window Size 224 | 7 256 | 8 386 | 12 512 | 16 Ideally, the window size should be a factor of the input resolution. In the third stage, we divide the resolution by 16, so the window size should be img_res/16/2 for the third stage and img_res/32 for the last stage. While this can be applied in a brute-force manner, a better way is to do model.change_window_size. Manual way to change resolution -> model.change_window_size(resolution) """ window_size = new_window_size print(f"Setting window size to {window_size}") for module in self.modules(): if hasattr(module, "window_size"): # check if tuple or a number if isinstance(module.window_size, tuple): if module.window_size[0] != window_size: module.window_size = (window_size, window_size) elif isinstance(module.window_size, list): if module.window_size[0] != window_size: module.window_size = [window_size, window_size] else: module.window_size = window_size
def set_optimal_window_size(self, image_dim, max_window_size = 16): """ Using hand picked window size for various resolutions.
E-RADIO employs windowed attention, which may be sensitive to the choice of this parameter, especially in cases of uneven partitioning of the feature maps. E-RADIO allows for the adjustment of the window size after training, making it adaptable to different input image resolutions. The recommended values for window size based on input resolution are as follows:
Input Resolution | Window Size 224 | 7 256 | 8 386 | 12 512 | 16 Ideally, the window size should be a factor of the input resolution. In the third stage, we divide the resolution by 16, so the window size should be img_res/16/2 for the third stage and img_res/32 for the last stage. While this can be applied in a brute-force manner, a better way is to do model.change_window_size. Manual way to change resolution -> model.change_window_size(resolution)
""" # import math
def divisorGenerator(n): large_divisors = [] for i in range(1, int(math.sqrt(n) + 1)): if n % i == 0: yield i if i*i != n: large_divisors.append(n / i) for divisor in reversed(large_divisors): yield divisor
if isinstance(image_dim, list) or isinstance(image_dim, tuple): image_dim = min(image_dim)
# we do windowed attention in the 3rd stage for the first time, therefore //16, # we do subsampled attention with downsample by 2 so need to get //32 actually # ideally we should rewrite this to be dependent on the structure of the model like what if subsampled is removed etc all_divisors = np.array(list(divisorGenerator(image_dim//32))) new_window_size = int(min(all_divisors[all_divisors <= max_window_size][-1], max_window_size))
# for image_dim in [128, 224, 256, 384, 512, 768, 1024]: # all_divisors = np.array(list(divisorGenerator(image_dim//32))) # new_window_size = int(min(all_divisors[all_divisors <= max_window_size][-1], max_window_size)) # print(f"Setting window size to {new_window_size} for image resolution {image_dim}")
self.change_window_size(new_window_size = new_window_size)
@register_modeldef eradio_large_fullres_ws16(pretrained=False, **kwargs): model = ERADIO( depths=[3, 3, 5, 5], num_heads=[2, 4, 8, 16], window_size=[None, None, [16, 16], 16], dim=192, in_dim=64, mlp_ratio=4, drop_path_rate=0.0, sr_ratio=[1, 1, [2, 1], 1], use_swiglu=False, yolo_arch=True, shuffle_down=False, conv_base=True, use_neck=True, full_features_head_dim=1536, neck_start_stage=2, **kwargs, ) if pretrained: model.load_state_dict(torch.load(pretrained)["state_dict"]) return model
@register_modeldef eradio_xxxtiny(pretrained=False, **kwargs): # , model = ERADIO( depths=[1, 3, 4, 5], num_heads=[2, 4, 8, 16], window_size=[None, None, [16, 16], 16], dim=32, in_dim=32, mlp_ratio=4, drop_path_rate=0.0, sr_ratio=[1, 1, [2, 1], 1], use_swiglu=False, yolo_arch=True, shuffle_down=False, conv_base=True, use_neck=True, full_features_head_dim=256, neck_start_stage=2, **kwargs, ) if pretrained: model.load_state_dict(torch.load(pretrained)) return model
@register_modeldef eradio_xxxtiny_8x_ws12(pretrained=False, **kwargs): model = ERADIO(depths=[1, 3, 4, 5], num_heads=[2, 4, 8, 16], window_size=[None, None, [12, 12], 12], dim=32, in_dim=32, mlp_ratio=4, drop_path_rate=0.0, sr_ratio=[1, 1, [2, 1], 1], use_swiglu=False, downsample_shuffle=False, yolo_arch=True, shuffle_down=False, cpb_mlp_hidden=64, use_neck=True, full_features_head_dim=256, neck_start_stage=2, conv_groups_ratio = 1, **kwargs) if pretrained: model.load_state_dict(torch.load(pretrained)["state_dict"]) return model
@register_modeldef eradio_xxxtiny_8x_ws16(pretrained=False, **kwargs): model = ERADIO(depths=[1, 3, 4, 5], num_heads=[2, 4, 8, 16], window_size=[None, None, [16, 16], 16], dim=32, in_dim=32, mlp_ratio=4, drop_path_rate=0.0, sr_ratio=[1, 1, [2, 1], 1], use_swiglu=False, downsample_shuffle=False, yolo_arch=True, shuffle_down=False, cpb_mlp_hidden=64, use_neck=True, full_features_head_dim=256, neck_start_stage=1, conv_groups_ratio = 1, **kwargs) if pretrained: model.load_state_dict(torch.load(pretrained)["state_dict"]) return model
@register_modeldef eradio(pretrained=False, **kwargs): return eradio_large_fullres_ws16(pretrained=pretrained, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# Copyright (c) 2023-2024, 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.
from torch import nn
from timm.models import register_modelfrom timm.models.vision_transformer import VisionTransformer, _create_vision_transformer, Mlp
@register_modeldef vit_tiny_patch14_224(pretrained=False, **kwargs) -> VisionTransformer: """ ViT-Tiny (Vit-Ti/16) """ model_args = dict(patch_size=14, embed_dim=192, depth=12, num_heads=3) model = _create_vision_transformer('vit_tiny_patch14_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model
@register_modeldef vit_small_patch14_224(pretrained=False, **kwargs) -> VisionTransformer: """ ViT-Small (ViT-S/16) """ model_args = dict(patch_size=14, embed_dim=384, depth=12, num_heads=6) model = _create_vision_transformer('vit_small_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model
@register_modeldef vit_base_patch14_224(pretrained=False, **kwargs) -> VisionTransformer: """ ViT-Base (ViT-B/14) from original paper (https://arxiv.org/abs/2010.11929). ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer. """ model_args = dict(patch_size=14, embed_dim=768, depth=12, num_heads=12) model = _create_vision_transformer('vit_base_patch14_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model
@register_modeldef vit_huge_patch16_224(pretrained=False, **kwargs) -> VisionTransformer: """ ViT-Huge model (ViT-H/16) from original paper (https://arxiv.org/abs/2010.11929). """ model_args = dict(patch_size=16, embed_dim=1280, depth=32, num_heads=16) if pretrained: # There is no pretrained version of ViT-H/16, but we can adapt a ViT-H/14 for this purpose model = _create_vision_transformer('vit_huge_patch14_clip_336', pretrained=True, **dict(model_args, pre_norm=True, **kwargs)) else: model = _create_vision_transformer('vit_huge_patch16_224', pretrained=False, **dict(model_args, **kwargs)) return model
@register_modeldef vit_huge_patch16_224_mlpnorm(pretrained=False, **kwargs) -> VisionTransformer: """ ViT-Huge model (ViT-H/16) from original paper (https://arxiv.org/abs/2010.11929). """ model = vit_huge_patch16_224(pretrained=pretrained, **kwargs)
for m in model.modules(): if isinstance(m, Mlp) and not isinstance(m.norm, nn.LayerNorm): m.norm = nn.LayerNorm(m.fc1.out_features)
return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from collections import namedtuplefrom typing import Callable, Optional, List, Union
from timm.models import VisionTransformerimport torchfrom torch import nnfrom transformers import PretrainedConfig, PreTrainedModel
from .common import RESOURCE_MAP, DEFAULT_VERSION
# Import all required modules.from .adaptor_base import AdaptorBase, RadioOutput, AdaptorInputfrom .adaptor_generic import GenericAdaptor, AdaptorBasefrom .adaptor_mlp import create_mlp_from_statefrom .adaptor_registry import adaptor_registryfrom .cls_token import ClsTokenfrom .enable_cpe_support import enable_cpefrom .enable_spectral_reparam import configure_spectral_reparam_from_argsfrom .eradio_model import eradiofrom .radio_model import create_model_from_argsfrom .radio_model import RADIOModel as RADIOModelBase, Resolutionfrom .input_conditioner import get_default_conditioner, InputConditionerfrom .open_clip_adaptor import OpenCLIP_RADIOfrom .vit_patch_generator import ViTPatchGeneratorfrom .vitdet import apply_vitdet_arch, VitDetArgs
# Register extra modelsfrom .extra_timm_models import *
class RADIOConfig(PretrainedConfig): """Pretrained Hugging Face configuration for RADIO models."""
def __init__( self, args: Optional[dict] = None, version: Optional[str] = DEFAULT_VERSION, patch_size: Optional[int] = None, max_resolution: Optional[int] = None, preferred_resolution: Optional[Resolution] = None, adaptor_names: Union[str, List[str]] = None, vitdet_window_size: Optional[int] = None, **kwargs, ): self.args = args for field in ["dtype", "amp_dtype"]: if self.args is not None and field in self.args: # Convert to a string in order to make it serializable. # For example for torch.float32 we will store "float32", # for "bfloat16" we will store "bfloat16". self.args[field] = str(args[field]).split(".")[-1] self.version = version resource = RESOURCE_MAP[version] self.patch_size = patch_size or resource.patch_size self.max_resolution = max_resolution or resource.max_resolution self.preferred_resolution = ( preferred_resolution or resource.preferred_resolution ) self.adaptor_names = adaptor_names self.vitdet_window_size = vitdet_window_size super().__init__(**kwargs)
class RADIOModel(PreTrainedModel): """Pretrained Hugging Face model for RADIO.
This class inherits from PreTrainedModel, which provides HuggingFace's functionality for loading and saving models. """
config_class = RADIOConfig
def __init__(self, config: RADIOConfig): super().__init__(config)
RADIOArgs = namedtuple("RADIOArgs", config.args.keys()) args = RADIOArgs(**config.args) self.config = config
model = create_model_from_args(args) input_conditioner: InputConditioner = get_default_conditioner()
dtype = getattr(args, "dtype", torch.float32) if isinstance(dtype, str): # Convert the dtype's string representation back to a dtype. dtype = getattr(torch, dtype) model.to(dtype=dtype) input_conditioner.dtype = dtype
summary_idxs = torch.tensor( [i for i, t in enumerate(args.teachers) if t.get("use_summary", True)], dtype=torch.int64, )
adaptor_names = config.adaptor_names if adaptor_names is not None: raise NotImplementedError( f"Adaptors are not yet supported in Hugging Face models. Adaptor names: {adaptor_names}" )
adaptors = dict()
self.radio_model = RADIOModelBase( model, input_conditioner, summary_idxs=summary_idxs, patch_size=config.patch_size, max_resolution=config.max_resolution, window_size=config.vitdet_window_size, preferred_resolution=config.preferred_resolution, adaptors=adaptors, )
@property def adaptors(self) -> nn.ModuleDict: return self.radio_model.adaptors
@property def model(self) -> VisionTransformer: return self.radio_model.model
@property def input_conditioner(self) -> InputConditioner: return self.radio_model.input_conditioner
@property def num_summary_tokens(self) -> int: return self.radio_model.num_summary_tokens
@property def patch_size(self) -> int: return self.radio_model.patch_size
@property def max_resolution(self) -> int: return self.radio_model.max_resolution
@property def preferred_resolution(self) -> Resolution: return self.radio_model.preferred_resolution
@property def window_size(self) -> int: return self.radio_model.window_size
@property def min_resolution_step(self) -> int: return self.radio_model.min_resolution_step
def make_preprocessor_external(self) -> Callable[[torch.Tensor], torch.Tensor]: return self.radio_model.make_preprocessor_external()
def get_nearest_supported_resolution(self, height: int, width: int) -> Resolution: return self.radio_model.get_nearest_supported_resolution(height, width)
def switch_to_deploy(self): return self.radio_model.switch_to_deploy()
def forward(self, x: torch.Tensor): return self.radio_model.forward(x)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Copyright (c) 2023-2024, 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.
from typing import Union, Tuple
import torchfrom torch import nn
norm_t = Union[Tuple[float, float, float], torch.Tensor]
class InputConditioner(nn.Module): def __init__(self, input_scale: float, norm_mean: norm_t, norm_std: norm_t, dtype: torch.dtype = None, ): super().__init__()
self.dtype = dtype
self.register_buffer("norm_mean", _to_tensor(norm_mean) / input_scale) self.register_buffer("norm_std", _to_tensor(norm_std) / input_scale)
def forward(self, x: torch.Tensor): y = (x - self.norm_mean) / self.norm_std if self.dtype is not None: y = y.to(self.dtype) return y
def get_default_conditioner(): from timm.data.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
return InputConditioner( input_scale=1.0, norm_mean=OPENAI_CLIP_MEAN, norm_std=OPENAI_CLIP_STD, )
def _to_tensor(v: norm_t): return torch.as_tensor(v, dtype=torch.float32).view(-1, 1, 1)123version https://git-lfs.github.com/spec/v1oid sha256:d9153ddb6c061bcf4ec299adcac9e83eda290bf56349138918714cc5e9b6417dsize 12795582161234567891011121314151617181920212223242526272829303132333435363738394041# 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 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.from argparse import Namespace
import torchfrom torch import nnimport torch.nn.functional as F
from .adaptor_registry import adaptor_registry, dict_t, state_t
from .adaptor_generic import GenericAdaptor
class OpenCLIP_RADIO(GenericAdaptor): def __init__(self, main_config: Namespace, adaptor_config: dict_t, state: state_t): super().__init__(main_config, adaptor_config, state)
import open_clip
self.oc_model = open_clip.create_model_from_pretrained( model_name=adaptor_config['model'], pretrained=adaptor_config['pretrained'], return_transform=False, ) # Unload these parameters self.oc_model.visual = None
self.tokenizer = open_clip.get_tokenizer(model_name=adaptor_config['model'])
def encode_text(self, text, normalize: bool = False): return self.oc_model.encode_text(text, normalize=normalize)
@adaptor_registry.register_adaptor("open_clip")def create_open_clip_adaptor(main_config: Namespace, adaptor_config: dict_t, state: state_t): return OpenCLIP_RADIO(main_config, adaptor_config, state)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257# Copyright (c) 2023-2024, 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.from typing import Callable, Dict, List, NamedTuple, Optional, Tuple, Union
import torchfrom torch import nn
from timm.models import create_model, VisionTransformer
from .enable_cpe_support import enable_cpefrom .input_conditioner import InputConditioner# Register extra modelsfrom . import extra_timm_modelsfrom .adaptor_base import AdaptorBase, RadioOutput, AdaptorInputfrom . import eradio_modelfrom .enable_spectral_reparam import configure_spectral_reparam_from_args
class Resolution(NamedTuple): height: int width: int
class RADIOModel(nn.Module): def __init__( self, model: nn.Module, input_conditioner: InputConditioner, patch_size: int, max_resolution: int, preferred_resolution: Resolution, summary_idxs: Optional[torch.Tensor] = None, window_size: int = None, adaptors: Dict[str, AdaptorBase] = None, ): super().__init__()
self.model = model self.input_conditioner = input_conditioner if summary_idxs is not None: self.register_buffer('summary_idxs', summary_idxs) else: self.summary_idxs = None
self._preferred_resolution = preferred_resolution self._patch_size = patch_size self._max_resolution = max_resolution self._window_size = window_size
adaptors = adaptors or dict() self.adaptors = nn.ModuleDict(adaptors)
@property def num_summary_tokens(self) -> int: patch_gen = getattr(self.model, "patch_generator", None) if patch_gen is not None: return patch_gen.num_skip elif self.model.global_pool == 'avg': return 0 return 1
@property def patch_size(self) -> int: if self._patch_size is not None: return self._patch_size patch_gen = getattr(self.model, "patch_generator", None) if patch_gen is not None: return patch_gen.patch_size return None
@property def max_resolution(self) -> int: return self._max_resolution
@property def preferred_resolution(self) -> Resolution: return self._preferred_resolution
@property def window_size(self) -> int: return self._window_size
@property def min_resolution_step(self) -> int: res = self.patch_size if self.window_size is not None: res *= self.window_size return res
def make_preprocessor_external(self) -> Callable[[torch.Tensor], torch.Tensor]: ret = self.input_conditioner self.input_conditioner = nn.Identity() return ret
def get_nearest_supported_resolution(self, height: int, width: int) -> Resolution: height = int(round(height / self.min_resolution_step) * self.min_resolution_step) width = int(round(width / self.min_resolution_step) * self.min_resolution_step)
height = max(height, self.min_resolution_step) width = max(width, self.min_resolution_step)
return Resolution(height=height, width=width)
def switch_to_deploy(self): fn = getattr(self.model, 'switch_to_deploy', None) if fn is not None: fn()
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: res_step = self.min_resolution_step if res_step is not None and (x.shape[-2] % res_step != 0 or x.shape[-1] % res_step != 0): raise ValueError('The input resolution must be a multiple of `self.min_resolution_step`. ' '`self.get_nearest_supported_resolution(<height>, <width>) is provided as a convenience API. ' f'Input: {x.shape[-2:]}, Nearest: {self.get_nearest_supported_resolution(*x.shape[-2:])}')
x = self.input_conditioner(x) y = self.model.forward_features(x)
if isinstance(self.model, VisionTransformer): patch_gen = getattr(self.model, "patch_generator", None) if patch_gen is not None: all_summary = y[:, : patch_gen.num_cls_tokens] if self.summary_idxs is not None: bb_summary = all_summary[:, self.summary_idxs] else: bb_summary = all_summary all_feat = y[:, patch_gen.num_skip :] elif self.model.global_pool == "avg": all_summary = y[:, self.model.num_prefix_tokens :].mean(dim=1) bb_summary = all_summary all_feat = y else: all_summary = y[:, 0] bb_summary = all_summary all_feat = y[:, 1:] elif isinstance(self.model, eradio_model.ERADIO): _, f = y all_feat = f.flatten(2).transpose(1, 2) all_summary = all_feat.mean(dim=1) bb_summary = all_summary elif isinstance(y, (list, tuple)): all_summary, all_feat = y bb_summary = all_summary else: raise ValueError("Unsupported model type")
all_feat = all_feat.float() ret = RadioOutput(bb_summary.flatten(1), all_feat).to(torch.float32) if self.adaptors: ret = dict(backbone=ret) for name, adaptor in self.adaptors.items(): if all_summary.ndim == 3: summary = all_summary[:, adaptor.head_idx] else: summary = all_summary ada_input = AdaptorInput(images=x, summary=summary.float(), features=all_feat) v = adaptor(ada_input).to(torch.float32) ret[name] = v
return ret
def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int], Tuple[int]]] = None, return_prefix_tokens: bool = False, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, aggregation: Optional[str] = "sparse", ) -> List[RadioOutput]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, select matching indices if sequence return_prefix_tokens: Return both prefix and spatial intermediate tokens norm: Apply norm layer to all intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features aggregation: intermediate layer aggregation method (sparse or dense). Dense accumulation is done by averaging the features in each group. Returns: List of RadioOutput objects. """ outputs = self.model.forward_intermediates( x, indices=indices, return_prefix_tokens=return_prefix_tokens, norm=norm, stop_early=stop_early, output_fmt=output_fmt, intermediates_only=intermediates_only, aggregation=aggregation, ) if return_prefix_tokens: radio_outputs = [RadioOutput(summary, features) for (summary, features) in outputs] else: radio_outputs = [RadioOutput(None, features) for features in outputs] return radio_outputs
def create_model_from_args(args) -> nn.Module: in_chans = 3 if args.in_chans is not None: in_chans = args.in_chans elif args.input_size is not None: in_chans = args.input_size[0]
# Skip weight initialization unless it's explicitly requested. weight_init = args.model_kwargs.pop("weight_init", "skip")
model = create_model( args.model, pretrained=args.pretrained, in_chans=in_chans, num_classes=args.num_classes, drop_rate=args.drop, drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, scriptable=args.torchscript, checkpoint_path=args.initial_checkpoint, weight_init=weight_init, **args.model_kwargs, )
if hasattr(model, 'norm') and not getattr(args, 'model_norm', False): model.norm = nn.Identity()
model.head = nn.Identity()
assert ( not args.cls_token_per_teacher or args.cpe_max_size is not None ), "CPE must be enabled for multiple CLS tokens!"
if args.cpe_max_size is not None: uq_teachers = set(t['name'] for t in args.teachers) enable_cpe( model, args.cpe_max_size, num_cls_tokens=len(uq_teachers) if args.cls_token_per_teacher else 1, register_multiple=args.register_multiple, )
if args.spectral_reparam: configure_spectral_reparam_from_args(model, args)
return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299# Copyright (c) 2023-2024, 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 Union, Tuple, Optional
import torchimport torch.nn.functional as Ffrom torch import nnfrom einops import rearrange
from .cls_token import ClsToken
input_dim_t = Union[int, Tuple[int, int]]
try: # raise ImportError() from indirect_grid_sample import indirect_grid_sampleexcept ImportError: indirect_grid_sample = None
class ViTPatchGenerator(nn.Module): def __init__(self, patch_size: int, embed_dim: int, input_dims: input_dim_t, abs_pos: bool = True, normalize_patches: bool = False, cls_token: bool = False, max_input_dims: Optional[input_dim_t] = None, pos_dropout: float = 0.0, return_pos_enc: bool = False, num_cls_tokens: int = 1, register_multiple: int = 0, device=None, dtype=None, ): super().__init__()
if isinstance(input_dims, int): input_dims = (input_dims, input_dims)
if max_input_dims is None: max_input_dims = input_dims if isinstance(max_input_dims, int): max_input_dims = (max_input_dims, max_input_dims)
max_input_dims = tuple( int(math.ceil(d / patch_size) * patch_size) for d in max_input_dims )
self.cpe_mode = max_input_dims != input_dims self.pos_dropout = pos_dropout self.return_pos_enc = return_pos_enc
factory = dict(device=device, dtype=dtype)
self.patch_size = patch_size self.abs_pos = abs_pos self.embed_dim = embed_dim
self.num_rows = max_input_dims[0] // patch_size self.num_cols = max_input_dims[1] // patch_size self.input_dims = tuple(d // patch_size for d in input_dims) self.num_patches = self.num_rows * self.num_cols self.max_input_dims = max_input_dims
self.im_to_patches = Im2Patches(patch_size) self.embedder = ViTPatchLinear(patch_size, embed_dim, **factory)
if abs_pos: scale = embed_dim ** -0.5 self.pos_embed = nn.Parameter(torch.randn(1, self.num_patches, embed_dim, **factory) * scale)
self.cls_token = ClsToken( embed_dim, num_tokens=num_cls_tokens, enabled=cls_token, register_multiple=register_multiple, )
self.patch_normalizer = nn.LayerNorm(embed_dim) if normalize_patches else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor: patches = self.embed_patches(x) patches, pos_enc = self.apply_pos_enc(patches, input_size=x.shape[2:]) patches = self.cls_token(patches) patches = self.patch_normalizer(patches) if self.return_pos_enc: return patches, pos_enc return patches
@property def apply_cls_token(self): return self.cls_token.enabled
@property def num_cls_tokens(self): return self.cls_token.num_tokens
@property def num_registers(self): return self.cls_token.num_registers
@property def num_skip(self): return self.num_cls_tokens + self.num_registers
def no_weight_decay(self): return [ 'pos_embed', ]
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): if self.abs_pos: self._load_embed(state_dict[f'{prefix}pos_embed'], self.pos_embed)
def _load_embed(self, src_embed: torch.Tensor, targ_embed: nn.Parameter): if src_embed.shape != targ_embed.shape: src_size = int(math.sqrt(src_embed.shape[1]))
assert src_size ** 2 == src_embed.shape[1], 'Unable to interpolate non-square embedding'
src_embed = rearrange(src_embed, 'b (h w) c -> b c h w', h=src_size, w=src_size) src_embed = F.interpolate(src_embed, size=(self.num_rows, self.num_cols), mode='bicubic', align_corners=True, antialias=False) src_embed = rearrange(src_embed, 'b c h w -> b (h w) c') targ_embed.data.copy_(src_embed)
def _load_projection(self, src_proj_weight: torch.Tensor, targ_proj_weight: torch.Tensor): if src_proj_weight.shape != targ_proj_weight.shape: src_patch_size = int(math.sqrt(src_proj_weight.shape[1] // 3))
assert (src_patch_size ** 2) * 3 == src_proj_weight.shape[1], 'Unable to interpolate non-square patch size'
src_proj_weight = rearrange(src_proj_weight, 'b (c h w) -> b c h w', c=3, h=src_patch_size, w=src_patch_size) src_proj_weight = F.interpolate(src_proj_weight, size=(self.patch_size, self.patch_size), mode='bicubic', align_corners=True, antialias=False) src_proj_weight = rearrange(src_proj_weight, 'b c h w -> b (c h w)') targ_proj_weight.data.copy_(src_proj_weight)
def embed_patches(self, x: torch.Tensor) -> torch.Tensor: patches = self.im_to_patches(x) patches = self.embedder(patches) return patches
def apply_pos_enc(self, patches: torch.Tensor, patch_idxs: Optional[torch.Tensor] = None, input_size: Optional[Tuple[int, int]] = None, ) -> torch.Tensor: if not self.abs_pos: return patches
pos_enc = self.get_pos_enc(patches.shape[0], patch_idxs, input_size)
if self.training and self.pos_dropout > 0: keeps = torch.rand(patches.shape[0], 1, 1, dtype=pos_enc.dtype, device=pos_enc.device) > self.pos_dropout pos_enc_drop = torch.where(keeps, pos_enc, 0) else: pos_enc_drop = pos_enc
return patches + pos_enc_drop, pos_enc
def get_pos_enc(self, batch_size: int, patch_idxs: Optional[torch.Tensor] = None, input_size: Optional[Tuple[int, int]] = None, ) -> torch.Tensor: if input_size is None: input_dims = self.input_dims else: input_dims = tuple(d // self.patch_size for d in input_size)
pos_embed = self._get_pos_embeddings(batch_size, input_dims)
if patch_idxs is None: return pos_embed
exp_patch_idxs = patch_idxs.unsqueeze(-1).expand(-1, -1, pos_embed.shape[-1])
pos_embed = torch.gather(pos_embed.expand(patch_idxs.shape[0], -1, -1), dim=1, index=exp_patch_idxs) return pos_embed
def _get_pos_embeddings(self, batch_size: int, input_dims: Tuple[int, int]): if (self.num_rows, self.num_cols) == input_dims: return self.pos_embed
pos_embed = self.pos_embed.reshape(1, self.num_rows, self.num_cols, -1).permute(0, 3, 1, 2)
def window_select(pos_embed): if input_dims[0] < pos_embed.shape[-2]: pos_embed = pos_embed[..., :input_dims[0], :] if input_dims[1] < pos_embed.shape[-1]: pos_embed = pos_embed[..., :, :input_dims[1]] return pos_embed
if self.cpe_mode: if self.training: min_scale = math.sqrt(0.1) scale = torch.rand(batch_size, 1, 1, device=pos_embed.device) * (1 - min_scale) + min_scale aspect_min = math.log(3 / 4) aspect_max = -aspect_min aspect = torch.exp(torch.rand(batch_size, 1, 1, device=pos_embed.device) * (aspect_max - aspect_min) + aspect_min)
scale_x = scale * aspect scale_y = scale * (1 / aspect) scale_xy = torch.stack([scale_x, scale_y], dim=-1).clamp_(0, 1)
pos_xy = torch.rand(batch_size, 1, 1, 2, device=pos_embed.device) * (1 - scale_xy)
lin_x = torch.linspace(0, 1, steps=input_dims[1], device=pos_embed.device)[None, None].expand(batch_size, input_dims[0], -1) lin_y = torch.linspace(0, 1, steps=input_dims[0], device=pos_embed.device)[None, :, None].expand(batch_size, -1, input_dims[1])
lin_xy = torch.stack([lin_x, lin_y], dim=-1)
grid_xy = lin_xy * scale_xy + pos_xy
# Convert to [-1, 1] range grid_xy.mul_(2).sub_(1)
pos_embed = F.grid_sample( pos_embed.float().expand(batch_size, -1, -1, -1), grid=grid_xy, mode='bilinear', padding_mode='zeros', align_corners=True, ).to(pos_embed.dtype) else: # i_rows, i_cols = input_dims # p_rows, p_cols = pos_embed.shape[2:] # if i_rows <= p_rows and i_cols <= p_cols: # left = (p_cols - i_cols) // 2 # top = (p_rows - i_rows) // 2 # pos_embed = pos_embed[..., top:top+i_rows, left:left+i_cols] # else: max_dim = max(input_dims) pos_embed = F.interpolate(pos_embed.float(), size=(max_dim, max_dim), align_corners=True, mode='bilinear').to(pos_embed.dtype)
pos_embed = window_select(pos_embed) else: pos_embed = window_select(pos_embed)
if pos_embed.shape[-2:] != input_dims: pos_embed = F.interpolate(pos_embed.float(), size=input_dims, align_corners=True, mode='bilinear').to(pos_embed.dtype)
pos_embed = pos_embed.flatten(2).permute(0, 2, 1)
return pos_embed
class Im2Patches(nn.Module): def __init__(self, patch_size: int): super().__init__() self.patch_size = patch_size
def forward(self, x: torch.Tensor) -> torch.Tensor: if self.patch_size == 1: patches = x.flatten(2) patches = patches.permute(0, 2, 1) return patches
py = x.shape[-2] // self.patch_size px = x.shape[-1] // self.patch_size patches = rearrange(x, 'b c (py yy) (px xx) -> b (py px) (c yy xx)', py=py, yy=self.patch_size, px=px, xx=self.patch_size, ) return patches
class ViTPatchLinear(nn.Linear): def __init__(self, patch_size: int, embed_dim: int, **factory): super().__init__( 3 * (patch_size ** 2), embed_dim, bias=False, **factory ) self.patch_size = patch_size
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): if self.bias is not None: self.bias.data.copy_(state_dict[f'{prefix}bias'])
chk_weight = state_dict[f'{prefix}weight'] if chk_weight.shape != self.weight.shape: src_patch_size = int(math.sqrt(chk_weight.shape[1] // 3))
assert (src_patch_size ** 2) * 3 == chk_weight.shape[1], 'Unable to interpolate non-square patch size'
chk_weight = rearrange(chk_weight, 'b (c h w) -> b c h w', c=3, h=src_patch_size, w=src_patch_size) chk_weight = F.interpolate(chk_weight, size=(self.patch_size, self.patch_size), mode='bicubic', align_corners=True, antialias=False) chk_weight = rearrange(chk_weight, 'b c h w -> b (c h w)') self.weight.data.copy_(chk_weight)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181from collections import defaultdictfrom contextlib import contextmanagerfrom logging import getLoggerimport mathimport sysfrom typing import List, Union, Iterable
import numpy as npimport torchfrom torch import nn
from timm.models import VisionTransformerfrom einops import rearrange
DEFAULT_NUM_WINDOWED = 5DEFAULT_NUM_GLOBAL = 4
class VitDetArgs: def __init__(self, window_size: int, num_summary_tokens: int, num_windowed: int = None, num_global: int = None, ): self.window_size = window_size self.num_summary_tokens = num_summary_tokens self.num_windowed = num_windowed self.num_global = num_global
def apply_vitdet_arch(model: VisionTransformer, args: VitDetArgs): if isinstance(model, VisionTransformer): patch_embed = getattr(model, 'patch_generator', model.patch_embed)
return ViTDetHook(patch_embed, model.blocks, args) else: print(f'Warning: Unable to apply VitDet aug!', file=sys.stderr)
class ViTDetHook: def __init__(self, embedder: nn.Module, blocks: nn.Sequential, args: VitDetArgs, ): self.blocks = blocks self.num_summary_tokens = args.num_summary_tokens self.window_size = args.window_size
self._input_resolution = None self._num_windows = None self._cls_patch = None self._order_cache = dict()
embedder.register_forward_pre_hook(self._enter_model)
# This will decide if we window-fy the patches # and enable vit-det for this iteration, and if so, # rearrange the patches for efficient mode switching blocks.register_forward_pre_hook(self._enter_blocks)
is_global = True if args.num_windowed is not None: period = args.num_windowed + 1 else: num_global = args.num_global or DEFAULT_NUM_GLOBAL period = max(len(blocks) // num_global, 1)
for i, layer in enumerate(blocks[:-1]): ctr = i % period if ctr == 0: layer.register_forward_pre_hook(self._to_windows) is_global = False elif ctr == period - 1: layer.register_forward_pre_hook(self._to_global) is_global = True
# Always ensure the final layer is a global layer if not is_global: blocks[-1].register_forward_pre_hook(self._to_global)
blocks.register_forward_hook(self._exit_model)
def _enter_model(self, _, input: List[torch.Tensor]): self._input_resolution = input[0].shape[-2:]
def _enter_blocks(self, _, input: List[torch.Tensor]): # print(f'{get_rank()} - ViTDet Window Size: {self._window_size}', file=sys.stderr)
patches = input[0] patches = self._rearrange_patches(patches)
return (patches,) + input[1:]
def _to_windows(self, _, input: List[torch.Tensor]): patches = input[0]
if self.num_summary_tokens: self._cls_patch = patches[:, :self.num_summary_tokens] patches = patches[:, self.num_summary_tokens:]
patches = rearrange( patches, 'b (p t) c -> (b p) t c', p=self._num_windows, t=self.window_size ** 2, )
return (patches,) + input[1:]
def _to_global(self, _, input: List[torch.Tensor]): patches = input[0]
patches = rearrange( patches, '(b p) t c -> b (p t) c', p=self._num_windows, t=self.window_size ** 2, b=patches.shape[0] // self._num_windows, )
if self.num_summary_tokens: patches = torch.cat([ self._cls_patch, patches, ], dim=1)
return (patches,) + input[1:]
def _exit_model(self, _, inputs: List[torch.Tensor], patches: torch.Tensor): # Return patches to their original order patch_order = self._order_cache[self._input_resolution][0] patch_order = patch_order.reshape(1, -1, 1).expand_as(patches)
ret_patches = torch.empty_like(patches) ret_patches = torch.scatter( ret_patches, dim=1, index=patch_order, src=patches, )
return ret_patches
def _rearrange_patches(self, patches: torch.Tensor): # We rearrange the patches so that we can efficiently # switch between windowed and global mode by just # reshaping the tensor
patch_order, self._num_windows = self._order_cache.get(self._input_resolution, (None, None)) if patch_order is None: num_feat_patches = patches.shape[1] - self.num_summary_tokens num_pixels = self._input_resolution[0] * self._input_resolution[1]
patch_size = int(round(math.sqrt(num_pixels / num_feat_patches))) rows = self._input_resolution[-2] // patch_size cols = self._input_resolution[-1] // patch_size
w_rows = rows // self.window_size w_cols = cols // self.window_size
patch_order = torch.arange(0, num_feat_patches, device=patches.device)
patch_order = rearrange( patch_order, '(wy py wx px) -> (wy wx py px)', wy=w_rows, wx=w_cols, py=self.window_size, px=self.window_size, )
if self.num_summary_tokens: patch_order = torch.cat([ torch.arange(self.num_summary_tokens, dtype=patch_order.dtype, device=patch_order.device), patch_order + self.num_summary_tokens, ])
self._num_windows = w_rows * w_cols self._order_cache[self._input_resolution] = ( patch_order, self._num_windows, )
patch_order = patch_order.reshape(1, -1, 1).expand_as(patches) patches = torch.gather(patches, dim=1, index=patch_order) return patchesREADME.mdAdded+199
adaptor_base.pyAdded+35
adaptor_generic.pyAdded+29
adaptor_mlp.pyAdded+150
adaptor_registry.pyAdded+37
cls_token.pyAdded+55
common.pyAdded+71
config.jsonAdded+221
enable_cpe_support.pyAdded+158
enable_spectral_reparam.pyAdded+227
eradio_model.pyAdded+1392
extra_timm_models.pyAdded+66
hf_model.pyAdded+174
input_conditioner.pyAdded+49
model.safetensorsAdded+3
open_clip_adaptor.pyAdded+41
radio_model.pyAdded+257
vit_patch_generator.pyAdded+299
vitdet.pyAdded+181