Upload model
Browse files- README.md +3 -0
- adaptor_base.py +35 -0
- cls_token.py +1 -1
- common.py +51 -0
- config.json +155 -32
- enable_cpe_support.py +1 -1
- eradio_model.py +1802 -0
- extra_timm_models.py +66 -0
- hf_model.py +62 -11
- input_conditioner.py +5 -5
- model.safetensors +3 -0
- radio_model.py +195 -0
- vit_patch_generator.py +3 -3
README.md
CHANGED
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
1 |
# AM-RADIO: Reduce All Domains Into One
|
2 |
|
3 |
Mike Ranzinger, Greg Heinrich, Jan Kautz, Pavlo Molchanov
|
|
|
1 |
+
---
|
2 |
+
{}
|
3 |
+
---
|
4 |
# AM-RADIO: Reduce All Domains Into One
|
5 |
|
6 |
Mike Ranzinger, Greg Heinrich, Jan Kautz, Pavlo Molchanov
|
adaptor_base.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
from argparse import Namespace
|
9 |
+
from typing import NamedTuple
|
10 |
+
|
11 |
+
import torch
|
12 |
+
from torch import nn
|
13 |
+
import torch.nn.functional as F
|
14 |
+
|
15 |
+
|
16 |
+
class AdaptorInput(NamedTuple):
|
17 |
+
images: torch.Tensor
|
18 |
+
summary: torch.Tensor
|
19 |
+
features: torch.Tensor
|
20 |
+
|
21 |
+
|
22 |
+
class RadioOutput(NamedTuple):
|
23 |
+
summary: torch.Tensor
|
24 |
+
features: torch.Tensor
|
25 |
+
|
26 |
+
def to(self, *args, **kwargs):
|
27 |
+
return RadioOutput(
|
28 |
+
self.summary.to(*args, **kwargs) if self.summary is not None else None,
|
29 |
+
self.features.to(*args, **kwargs) if self.features is not None else None,
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
class AdaptorBase(nn.Module):
|
34 |
+
def forward(self, input: AdaptorInput) -> RadioOutput:
|
35 |
+
raise NotImplementedError("Subclasses must implement this!")
|
cls_token.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
common.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
|
9 |
+
from dataclasses import dataclass
|
10 |
+
|
11 |
+
from .radio_model import Resolution
|
12 |
+
|
13 |
+
|
14 |
+
@dataclass
|
15 |
+
class RadioResource:
|
16 |
+
url: str
|
17 |
+
patch_size: int
|
18 |
+
max_resolution: int
|
19 |
+
preferred_resolution: Resolution
|
20 |
+
|
21 |
+
|
22 |
+
RESOURCE_MAP = {
|
23 |
+
# RADIO
|
24 |
+
"radio_v2.1": RadioResource(
|
25 |
+
"https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.1_bf16.pth.tar?download=true",
|
26 |
+
patch_size=16,
|
27 |
+
max_resolution=2048,
|
28 |
+
preferred_resolution=Resolution(432, 432),
|
29 |
+
),
|
30 |
+
"radio_v2": RadioResource(
|
31 |
+
"https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.pth.tar?download=true",
|
32 |
+
patch_size=16,
|
33 |
+
max_resolution=2048,
|
34 |
+
preferred_resolution=Resolution(432, 432),
|
35 |
+
),
|
36 |
+
"radio_v1": RadioResource(
|
37 |
+
"https://huggingface.co/nvidia/RADIO/resolve/main/radio_v1.pth.tar?download=true",
|
38 |
+
patch_size=14,
|
39 |
+
max_resolution=1050,
|
40 |
+
preferred_resolution=Resolution(378, 378),
|
41 |
+
),
|
42 |
+
# E-RADIO
|
43 |
+
"e-radio_v2": RadioResource(
|
44 |
+
"https://huggingface.co/nvidia/RADIO/resolve/main/eradio_v2.pth.tar?download=true",
|
45 |
+
patch_size=16,
|
46 |
+
max_resolution=2048,
|
47 |
+
preferred_resolution=Resolution(512, 512),
|
48 |
+
),
|
49 |
+
}
|
50 |
+
|
51 |
+
DEFAULT_VERSION = "radio_v2.1"
|
config.json
CHANGED
@@ -1,21 +1,23 @@
|
|
1 |
{
|
|
|
2 |
"architectures": [
|
3 |
"RADIOModel"
|
4 |
],
|
5 |
"args": {
|
6 |
"aa": null,
|
7 |
-
"amp":
|
8 |
-
"amp_dtype": "
|
9 |
"amp_impl": "native",
|
10 |
"aug_repeats": 0,
|
11 |
"aug_splits": 0,
|
12 |
-
"auto_loss_balance_mode": "
|
13 |
"batch_size": 32,
|
14 |
"bn_eps": null,
|
15 |
"bn_momentum": null,
|
16 |
"cache_dir": null,
|
17 |
"channels_last": false,
|
18 |
"checkpoint_hist": 10,
|
|
|
19 |
"class_map": "",
|
20 |
"clip_grad": null,
|
21 |
"clip_mode": "norm",
|
@@ -24,13 +26,22 @@
|
|
24 |
"coco_image_dir": "/datasets/coco2017-adlsa/val2017",
|
25 |
"color_jitter": 0.4,
|
26 |
"cooldown_epochs": 0,
|
27 |
-
"cpe_max_size":
|
28 |
"crd_loss": false,
|
29 |
"crd_loss_weight": 0.8,
|
30 |
"crop_pct": null,
|
31 |
"cutmix": 0.0,
|
32 |
"cutmix_minmax": null,
|
33 |
-
"data_dir":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
"dataset": "nvgpt4",
|
35 |
"dataset_download": false,
|
36 |
"debug_full_knn": false,
|
@@ -48,8 +59,9 @@
|
|
48 |
"drop_block": null,
|
49 |
"drop_connect": null,
|
50 |
"drop_path": null,
|
|
|
51 |
"epoch_repeats": 0.0,
|
52 |
-
"epochs":
|
53 |
"eval": false,
|
54 |
"eval_metric": "knn_top1",
|
55 |
"eval_teacher": false,
|
@@ -59,8 +71,10 @@
|
|
59 |
"fast_norm": false,
|
60 |
"feature_summarizer": "cls_token",
|
61 |
"feature_upscale_factor": null,
|
|
|
|
|
62 |
"fuser": "",
|
63 |
-
"gp":
|
64 |
"grad_accum_steps": 1,
|
65 |
"grad_checkpointing": false,
|
66 |
"head_init_bias": null,
|
@@ -90,6 +104,10 @@
|
|
90 |
"lr_noise_pct": 0.67,
|
91 |
"lr_noise_std": 1.0,
|
92 |
"mean": null,
|
|
|
|
|
|
|
|
|
93 |
"min_lr": 0,
|
94 |
"mixup": 0.0,
|
95 |
"mixup_mode": "batch",
|
@@ -99,22 +117,32 @@
|
|
99 |
"mlp_hidden_size": 1520,
|
100 |
"mlp_num_inner": 3,
|
101 |
"mlp_version": "v2",
|
102 |
-
"model": "
|
103 |
-
"model_ema":
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
"model_kwargs": {},
|
|
|
107 |
"momentum": 0.9,
|
108 |
"no_aug": false,
|
109 |
"no_ddp_bb": false,
|
110 |
"no_prefetcher": false,
|
111 |
"no_resume_opt": false,
|
112 |
"num_classes": null,
|
113 |
-
"opt": "
|
114 |
"opt_betas": null,
|
115 |
"opt_eps": null,
|
116 |
-
"opt_kwargs": {
|
117 |
-
|
|
|
|
|
118 |
"patience_epochs": 10,
|
119 |
"pin_mem": false,
|
120 |
"prefetcher": true,
|
@@ -126,11 +154,11 @@
|
|
126 |
],
|
127 |
"recount": 1,
|
128 |
"recovery_interval": 0,
|
129 |
-
"register_multiple":
|
130 |
"remode": "pixel",
|
131 |
"reprob": 0.0,
|
132 |
"resplit": false,
|
133 |
-
"resume": "/lustre/fs6/portfolios/llmservice/users/mranzinger/output/evfm/
|
134 |
"save_images": false,
|
135 |
"scale": [
|
136 |
0.5,
|
@@ -140,26 +168,40 @@
|
|
140 |
"sched_on_updates": true,
|
141 |
"seed": 42,
|
142 |
"smoothing": 0.1,
|
|
|
143 |
"split_bn": false,
|
144 |
"start_epoch": null,
|
145 |
"std": null,
|
146 |
"steps_per_epoch": 2000,
|
147 |
"sync_bn": false,
|
148 |
-
"synchronize_step":
|
149 |
"teachers": [
|
150 |
{
|
151 |
"amp": true,
|
152 |
"amp_dtype": "bfloat16",
|
153 |
"batch_size": 16,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
"fd_loss_weight": 1.0,
|
155 |
"fd_normalize": false,
|
156 |
"feature_distillation": true,
|
157 |
"input_size": 378,
|
|
|
158 |
"model": "ViT-H-14-378-quickgelu",
|
159 |
"name": "clip",
|
160 |
"pretrained": "dfn5b",
|
161 |
"sample_rate": 16,
|
|
|
162 |
"summary_loss_weight": 1.0,
|
|
|
163 |
"type": "open_clip",
|
164 |
"vitdet_prob": 0.05,
|
165 |
"vitdet_window_sizes": [
|
@@ -177,11 +219,13 @@
|
|
177 |
"fd_normalize": false,
|
178 |
"feature_distillation": true,
|
179 |
"input_size": 336,
|
|
|
180 |
"model": "ViT-L/14@336px",
|
181 |
"name": "openai_clip",
|
182 |
"pretrained": "openai",
|
183 |
"sample_rate": 16,
|
184 |
"summary_loss_weight": 0.8,
|
|
|
185 |
"type": "openai_clip",
|
186 |
"use_summary": false
|
187 |
},
|
@@ -189,15 +233,87 @@
|
|
189 |
"amp": true,
|
190 |
"amp_dtype": "bfloat16",
|
191 |
"batch_size": 16,
|
192 |
-
"fd_loss_weight":
|
193 |
"fd_normalize": false,
|
194 |
"feature_distillation": true,
|
195 |
-
"input_size":
|
196 |
-
"model": "
|
197 |
"name": "dino_v2",
|
198 |
"sample_rate": 16,
|
199 |
"summary_loss_weight": 1.0,
|
|
|
200 |
"type": "dino_v2"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
}
|
202 |
],
|
203 |
"torchcompile": null,
|
@@ -208,30 +324,37 @@
|
|
208 |
"use_coco": false,
|
209 |
"use_multi_epochs_loader": false,
|
210 |
"val_data_dir": "/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/classification/imagenet-1k/webdataset",
|
211 |
-
"
|
|
|
|
|
212 |
"val_split": "val",
|
213 |
-
"validation_batch_size":
|
214 |
"vflip": 0.0,
|
215 |
"wandb_entity": "",
|
216 |
-
"wandb_group": "
|
217 |
"wandb_job_type": "",
|
218 |
"wandb_name": "",
|
219 |
"wandb_project": "",
|
220 |
-
"warmup_epochs":
|
221 |
"warmup_lr": 1e-05,
|
222 |
"warmup_prefix": false,
|
223 |
-
"weight_decay":
|
224 |
"worker_seeding": "all",
|
225 |
-
"workers":
|
226 |
-
"world_size":
|
227 |
},
|
228 |
"auto_map": {
|
229 |
"AutoConfig": "hf_model.RADIOConfig",
|
230 |
"AutoModel": "hf_model.RADIOModel"
|
231 |
},
|
232 |
-
"
|
233 |
-
"
|
234 |
-
"
|
235 |
-
|
236 |
-
|
|
|
|
|
|
|
|
|
|
|
237 |
}
|
|
|
1 |
{
|
2 |
+
"adaptor_names": null,
|
3 |
"architectures": [
|
4 |
"RADIOModel"
|
5 |
],
|
6 |
"args": {
|
7 |
"aa": null,
|
8 |
+
"amp": false,
|
9 |
+
"amp_dtype": "float16",
|
10 |
"amp_impl": "native",
|
11 |
"aug_repeats": 0,
|
12 |
"aug_splits": 0,
|
13 |
+
"auto_loss_balance_mode": "manual",
|
14 |
"batch_size": 32,
|
15 |
"bn_eps": null,
|
16 |
"bn_momentum": null,
|
17 |
"cache_dir": null,
|
18 |
"channels_last": false,
|
19 |
"checkpoint_hist": 10,
|
20 |
+
"chk_keep_forever": 10,
|
21 |
"class_map": "",
|
22 |
"clip_grad": null,
|
23 |
"clip_mode": "norm",
|
|
|
26 |
"coco_image_dir": "/datasets/coco2017-adlsa/val2017",
|
27 |
"color_jitter": 0.4,
|
28 |
"cooldown_epochs": 0,
|
29 |
+
"cpe_max_size": 2048,
|
30 |
"crd_loss": false,
|
31 |
"crd_loss_weight": 0.8,
|
32 |
"crop_pct": null,
|
33 |
"cutmix": 0.0,
|
34 |
"cutmix_minmax": null,
|
35 |
+
"data_dir": [
|
36 |
+
[
|
37 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/captioning/datacomp/dc1b/stage2",
|
38 |
+
0.95
|
39 |
+
],
|
40 |
+
[
|
41 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/segmentation/sam/stage1",
|
42 |
+
0.05
|
43 |
+
]
|
44 |
+
],
|
45 |
"dataset": "nvgpt4",
|
46 |
"dataset_download": false,
|
47 |
"debug_full_knn": false,
|
|
|
59 |
"drop_block": null,
|
60 |
"drop_connect": null,
|
61 |
"drop_path": null,
|
62 |
+
"dtype": "bfloat16",
|
63 |
"epoch_repeats": 0.0,
|
64 |
+
"epochs": 50,
|
65 |
"eval": false,
|
66 |
"eval_metric": "knn_top1",
|
67 |
"eval_teacher": false,
|
|
|
71 |
"fast_norm": false,
|
72 |
"feature_summarizer": "cls_token",
|
73 |
"feature_upscale_factor": null,
|
74 |
+
"force_new_wandb_id": false,
|
75 |
+
"force_spectral_reparam": false,
|
76 |
"fuser": "",
|
77 |
+
"gp": null,
|
78 |
"grad_accum_steps": 1,
|
79 |
"grad_checkpointing": false,
|
80 |
"head_init_bias": null,
|
|
|
104 |
"lr_noise_pct": 0.67,
|
105 |
"lr_noise_std": 1.0,
|
106 |
"mean": null,
|
107 |
+
"mesa": {
|
108 |
+
"gaussian_kl": false,
|
109 |
+
"start_epoch": 100
|
110 |
+
},
|
111 |
"min_lr": 0,
|
112 |
"mixup": 0.0,
|
113 |
"mixup_mode": "batch",
|
|
|
117 |
"mlp_hidden_size": 1520,
|
118 |
"mlp_num_inner": 3,
|
119 |
"mlp_version": "v2",
|
120 |
+
"model": "vit_huge_patch16_224_mlpnorm",
|
121 |
+
"model_ema": {
|
122 |
+
"decay": 0.9998,
|
123 |
+
"force_cpu": false,
|
124 |
+
"power": false,
|
125 |
+
"power_stds": [
|
126 |
+
0.05,
|
127 |
+
0.1
|
128 |
+
],
|
129 |
+
"start_epoch": 0
|
130 |
+
},
|
131 |
"model_kwargs": {},
|
132 |
+
"model_norm": true,
|
133 |
"momentum": 0.9,
|
134 |
"no_aug": false,
|
135 |
"no_ddp_bb": false,
|
136 |
"no_prefetcher": false,
|
137 |
"no_resume_opt": false,
|
138 |
"num_classes": null,
|
139 |
+
"opt": "lamb",
|
140 |
"opt_betas": null,
|
141 |
"opt_eps": null,
|
142 |
+
"opt_kwargs": {
|
143 |
+
"filter_bias_and_bn": false
|
144 |
+
},
|
145 |
+
"output": "/lustre/fs6/portfolios/llmservice/users/mranzinger/output/evfm/ohem/3-13-24_vit-h-16_bf16_ep50",
|
146 |
"patience_epochs": 10,
|
147 |
"pin_mem": false,
|
148 |
"prefetcher": true,
|
|
|
154 |
],
|
155 |
"recount": 1,
|
156 |
"recovery_interval": 0,
|
157 |
+
"register_multiple": 16,
|
158 |
"remode": "pixel",
|
159 |
"reprob": 0.0,
|
160 |
"resplit": false,
|
161 |
+
"resume": "/lustre/fs6/portfolios/llmservice/users/mranzinger/output/evfm/ohem/3-13-24_vit-h-16_bf16_ep50/checkpoints/checkpoint-48.pth.tar",
|
162 |
"save_images": false,
|
163 |
"scale": [
|
164 |
0.5,
|
|
|
168 |
"sched_on_updates": true,
|
169 |
"seed": 42,
|
170 |
"smoothing": 0.1,
|
171 |
+
"spectral_reparam": false,
|
172 |
"split_bn": false,
|
173 |
"start_epoch": null,
|
174 |
"std": null,
|
175 |
"steps_per_epoch": 2000,
|
176 |
"sync_bn": false,
|
177 |
+
"synchronize_step": true,
|
178 |
"teachers": [
|
179 |
{
|
180 |
"amp": true,
|
181 |
"amp_dtype": "bfloat16",
|
182 |
"batch_size": 16,
|
183 |
+
"data_dir": [
|
184 |
+
[
|
185 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/captioning/datacomp/dc1b/stage2",
|
186 |
+
0.95
|
187 |
+
],
|
188 |
+
[
|
189 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/segmentation/sam/stage1",
|
190 |
+
0.05
|
191 |
+
]
|
192 |
+
],
|
193 |
"fd_loss_weight": 1.0,
|
194 |
"fd_normalize": false,
|
195 |
"feature_distillation": true,
|
196 |
"input_size": 378,
|
197 |
+
"match_pre_proj": false,
|
198 |
"model": "ViT-H-14-378-quickgelu",
|
199 |
"name": "clip",
|
200 |
"pretrained": "dfn5b",
|
201 |
"sample_rate": 16,
|
202 |
+
"student_resolution": 432,
|
203 |
"summary_loss_weight": 1.0,
|
204 |
+
"torchcompile": true,
|
205 |
"type": "open_clip",
|
206 |
"vitdet_prob": 0.05,
|
207 |
"vitdet_window_sizes": [
|
|
|
219 |
"fd_normalize": false,
|
220 |
"feature_distillation": true,
|
221 |
"input_size": 336,
|
222 |
+
"match_pre_proj": false,
|
223 |
"model": "ViT-L/14@336px",
|
224 |
"name": "openai_clip",
|
225 |
"pretrained": "openai",
|
226 |
"sample_rate": 16,
|
227 |
"summary_loss_weight": 0.8,
|
228 |
+
"torchcompile": true,
|
229 |
"type": "openai_clip",
|
230 |
"use_summary": false
|
231 |
},
|
|
|
233 |
"amp": true,
|
234 |
"amp_dtype": "bfloat16",
|
235 |
"batch_size": 16,
|
236 |
+
"fd_loss_weight": 2.0,
|
237 |
"fd_normalize": false,
|
238 |
"feature_distillation": true,
|
239 |
+
"input_size": 378,
|
240 |
+
"model": "dinov2_vitg14_reg",
|
241 |
"name": "dino_v2",
|
242 |
"sample_rate": 16,
|
243 |
"summary_loss_weight": 1.0,
|
244 |
+
"torchcompile": true,
|
245 |
"type": "dino_v2"
|
246 |
+
},
|
247 |
+
{
|
248 |
+
"amp": false,
|
249 |
+
"batch_size": 2,
|
250 |
+
"data_dir": [
|
251 |
+
[
|
252 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/segmentation/sam/stage1",
|
253 |
+
0.4
|
254 |
+
]
|
255 |
+
],
|
256 |
+
"fd_loss_fn": "MSE",
|
257 |
+
"fd_loss_weight": 0.25,
|
258 |
+
"fd_normalize": false,
|
259 |
+
"fd_ohem": true,
|
260 |
+
"feature_distillation": true,
|
261 |
+
"input_size": 1024,
|
262 |
+
"model": "vit-h",
|
263 |
+
"name": "sam",
|
264 |
+
"sample_rate": 2,
|
265 |
+
"student_resolution": 1024,
|
266 |
+
"summary_loss_weight": 1e-05,
|
267 |
+
"type": "sam",
|
268 |
+
"use_summary": false,
|
269 |
+
"vitdet_prob": 0.99,
|
270 |
+
"vitdet_window_sizes": [
|
271 |
+
8,
|
272 |
+
16,
|
273 |
+
16
|
274 |
+
]
|
275 |
+
},
|
276 |
+
{
|
277 |
+
"amp": true,
|
278 |
+
"batch_size": 2,
|
279 |
+
"data_dir": [
|
280 |
+
[
|
281 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/ocr/publaynet/webdataset",
|
282 |
+
0.4
|
283 |
+
],
|
284 |
+
[
|
285 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/ocr/staging/arxiv/hocr",
|
286 |
+
0.4
|
287 |
+
],
|
288 |
+
[
|
289 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/ocr/scene-text/scene-text/text_ocr/webdataset",
|
290 |
+
0.15
|
291 |
+
],
|
292 |
+
[
|
293 |
+
"/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/ocr/scene-text/scene-text/hiertext/webdataset",
|
294 |
+
0.05
|
295 |
+
]
|
296 |
+
],
|
297 |
+
"fd_loss_fn": "MSE",
|
298 |
+
"fd_loss_weight": 0.13,
|
299 |
+
"fd_normalize": false,
|
300 |
+
"fd_ohem": true,
|
301 |
+
"fd_upsample_factor": 4,
|
302 |
+
"feature_distillation": true,
|
303 |
+
"input_size": 1024,
|
304 |
+
"model": "quality",
|
305 |
+
"name": "rtx-translate",
|
306 |
+
"sample_rate": 2,
|
307 |
+
"student_resolution": 1024,
|
308 |
+
"summary_loss_weight": 1e-05,
|
309 |
+
"type": "rtx_translate",
|
310 |
+
"use_summary": false,
|
311 |
+
"vitdet_prob": 0.99,
|
312 |
+
"vitdet_window_sizes": [
|
313 |
+
8,
|
314 |
+
16,
|
315 |
+
16
|
316 |
+
]
|
317 |
}
|
318 |
],
|
319 |
"torchcompile": null,
|
|
|
324 |
"use_coco": false,
|
325 |
"use_multi_epochs_loader": false,
|
326 |
"val_data_dir": "/lustre/fsw/portfolios/llmservice/projects/llmservice_nlp_fm/datasets/classification/imagenet-1k/webdataset",
|
327 |
+
"val_ema_only": false,
|
328 |
+
"val_img_size": 432,
|
329 |
+
"val_jobs_script": "run_validation_jobs_vit-h-16.sh",
|
330 |
"val_split": "val",
|
331 |
+
"validation_batch_size": 64,
|
332 |
"vflip": 0.0,
|
333 |
"wandb_entity": "",
|
334 |
+
"wandb_group": "ohem",
|
335 |
"wandb_job_type": "",
|
336 |
"wandb_name": "",
|
337 |
"wandb_project": "",
|
338 |
+
"warmup_epochs": 0.5,
|
339 |
"warmup_lr": 1e-05,
|
340 |
"warmup_prefix": false,
|
341 |
+
"weight_decay": 0.02,
|
342 |
"worker_seeding": "all",
|
343 |
+
"workers": 8,
|
344 |
+
"world_size": 128
|
345 |
},
|
346 |
"auto_map": {
|
347 |
"AutoConfig": "hf_model.RADIOConfig",
|
348 |
"AutoModel": "hf_model.RADIOModel"
|
349 |
},
|
350 |
+
"max_resolution": 2048,
|
351 |
+
"patch_size": 16,
|
352 |
+
"preferred_resolution": [
|
353 |
+
432,
|
354 |
+
432
|
355 |
+
],
|
356 |
+
"torch_dtype": "bfloat16",
|
357 |
+
"transformers_version": "4.37.2",
|
358 |
+
"version": "radio_v2.1",
|
359 |
+
"vitdet_window_size": null
|
360 |
}
|
enable_cpe_support.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
eradio_model.py
ADDED
@@ -0,0 +1,1802 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
6 |
+
# and proprietary rights in and to this software, related documentation
|
7 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
8 |
+
# distribution of this software and related documentation without an express
|
9 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
10 |
+
|
11 |
+
# E-RADIO (FasterViTv2) model from
|
12 |
+
# Mike Ranzinger, Greg Heinrich, Jan Kautz, and Pavlo Molchanov. "AM-RADIO: Agglomerative Model--Reduce All Domains Into One." arXiv preprint arXiv:2312.06709 (2023).
|
13 |
+
|
14 |
+
# based on FasterViT, Swin Transformer, YOLOv8
|
15 |
+
|
16 |
+
# FasterViT:
|
17 |
+
# 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).
|
18 |
+
|
19 |
+
import timm
|
20 |
+
import torch
|
21 |
+
import torch.nn as nn
|
22 |
+
from timm.models.registry import register_model
|
23 |
+
|
24 |
+
from timm.models.layers import trunc_normal_, DropPath, LayerNorm2d
|
25 |
+
import numpy as np
|
26 |
+
import torch.nn.functional as F
|
27 |
+
import math
|
28 |
+
import warnings
|
29 |
+
|
30 |
+
#######################
|
31 |
+
## Codebase from YOLOv8
|
32 |
+
## BEGINNING
|
33 |
+
#######################
|
34 |
+
|
35 |
+
class C2f(nn.Module):
|
36 |
+
"""Faster Implementation of CSP Bottleneck with 2 convolutions."""
|
37 |
+
"""From YOLOv8 codebase"""
|
38 |
+
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
|
39 |
+
super().__init__()
|
40 |
+
if drop_path is None:
|
41 |
+
drop_path = [0.0] * n
|
42 |
+
|
43 |
+
self.c = int(c2 * e) # hidden channels
|
44 |
+
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
|
45 |
+
self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
|
46 |
+
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))
|
47 |
+
|
48 |
+
def forward(self, x):
|
49 |
+
"""Forward pass through C2f layer."""
|
50 |
+
y = list(self.cv1(x).chunk(2, 1))
|
51 |
+
y.extend(m(y[-1]) for m in self.m)
|
52 |
+
return self.cv2(torch.cat(y, 1))
|
53 |
+
|
54 |
+
def forward_split(self, x):
|
55 |
+
"""Forward pass using split() instead of chunk()."""
|
56 |
+
y = list(self.cv1(x).split((self.c, self.c), 1))
|
57 |
+
y.extend(m(y[-1]) for m in self.m)
|
58 |
+
return self.cv2(torch.cat(y, 1))
|
59 |
+
|
60 |
+
class Bottleneck(nn.Module):
|
61 |
+
"""Standard bottleneck."""
|
62 |
+
|
63 |
+
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
|
64 |
+
super().__init__()
|
65 |
+
c_ = int(c2 * e) # hidden channels
|
66 |
+
self.cv1 = Conv(c1, c_, k[0], 1)
|
67 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
68 |
+
self.add = shortcut and c1 == c2
|
69 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
70 |
+
|
71 |
+
def forward(self, x):
|
72 |
+
"""'forward()' applies the YOLOv5 FPN to input data."""
|
73 |
+
return x + self.drop_path1(self.cv2(self.cv1(x))) if self.add else self.cv2(self.cv1(x))
|
74 |
+
|
75 |
+
|
76 |
+
class Conv(nn.Module):
|
77 |
+
"""Modified to support layer fusion"""
|
78 |
+
default_act = nn.SiLU() # default activation
|
79 |
+
|
80 |
+
def __init__(self, a, b, kernel_size=1, stride=1, padding=None, g=1, dilation=1, bn_weight_init=1, bias=False, act=True):
|
81 |
+
super().__init__()
|
82 |
+
|
83 |
+
self.conv = torch.nn.Conv2d(a, b, kernel_size, stride, autopad(kernel_size, padding, dilation), dilation, g, bias=False)
|
84 |
+
if 1:
|
85 |
+
self.bn = torch.nn.BatchNorm2d(b)
|
86 |
+
torch.nn.init.constant_(self.bn.weight, bn_weight_init)
|
87 |
+
torch.nn.init.constant_(self.bn.bias, 0)
|
88 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
89 |
+
|
90 |
+
|
91 |
+
def forward(self,x):
|
92 |
+
x = self.conv(x)
|
93 |
+
x = self.bn(x)
|
94 |
+
x = self.act(x)
|
95 |
+
return x
|
96 |
+
|
97 |
+
@torch.no_grad()
|
98 |
+
def switch_to_deploy(self):
|
99 |
+
# return 1
|
100 |
+
if not isinstance(self.bn, nn.Identity):
|
101 |
+
c, bn = self.conv, self.bn
|
102 |
+
w = bn.weight / (bn.running_var + bn.eps) ** 0.5
|
103 |
+
w = c.weight * w[:, None, None, None]
|
104 |
+
b = bn.bias - bn.running_mean * bn.weight / \
|
105 |
+
(bn.running_var + bn.eps)**0.5
|
106 |
+
|
107 |
+
self.conv.weight.data.copy_(w)
|
108 |
+
self.conv.bias = nn.Parameter(b)
|
109 |
+
|
110 |
+
self.bn = nn.Identity()
|
111 |
+
|
112 |
+
def autopad(k, p=None, d=1): # kernel, padding, dilation
|
113 |
+
"""Pad to 'same' shape outputs."""
|
114 |
+
if d > 1:
|
115 |
+
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
|
116 |
+
if p is None:
|
117 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
118 |
+
return p
|
119 |
+
|
120 |
+
|
121 |
+
#######################
|
122 |
+
## Codebase from YOLOv8
|
123 |
+
## END
|
124 |
+
#######################
|
125 |
+
|
126 |
+
def pixel_unshuffle(data, factor=2):
|
127 |
+
# performs nn.PixelShuffle(factor) in reverse, torch has some bug for ONNX and TRT, so doing it manually
|
128 |
+
B, C, H, W = data.shape
|
129 |
+
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)
|
130 |
+
|
131 |
+
class SwiGLU(nn.Module):
|
132 |
+
# should be more advanced, but doesnt improve results so far
|
133 |
+
def forward(self, x):
|
134 |
+
x, gate = x.chunk(2, dim=-1)
|
135 |
+
return F.silu(gate) * x
|
136 |
+
|
137 |
+
|
138 |
+
def window_partition(x, window_size):
|
139 |
+
"""
|
140 |
+
Function for partitioning image into windows and later do windowed attention
|
141 |
+
Args:
|
142 |
+
x: (B, C, H, W)
|
143 |
+
window_size: window size
|
144 |
+
Returns:
|
145 |
+
windows - local window features (num_windows*B, window_size*window_size, C)
|
146 |
+
(Hp, Wp) - the size of the padded image
|
147 |
+
"""
|
148 |
+
B, C, H, W = x.shape
|
149 |
+
|
150 |
+
if window_size == 0 or (window_size==H and window_size==W):
|
151 |
+
windows = x.flatten(2).transpose(1, 2)
|
152 |
+
Hp, Wp = H, W
|
153 |
+
else:
|
154 |
+
pad_h = (window_size - H % window_size) % window_size
|
155 |
+
pad_w = (window_size - W % window_size) % window_size
|
156 |
+
if pad_h > 0 or pad_w > 0:
|
157 |
+
x = F.pad(x, (0, pad_w, 0, pad_h), mode="reflect")
|
158 |
+
Hp, Wp = H + pad_h, W + pad_w
|
159 |
+
|
160 |
+
x = x.view(B, C, Hp // window_size, window_size, Wp // window_size, window_size)
|
161 |
+
windows = x.permute(0, 2, 4, 3, 5, 1).reshape(-1, window_size*window_size, C)
|
162 |
+
|
163 |
+
return windows, (Hp, Wp)
|
164 |
+
|
165 |
+
class Conv2d_BN(nn.Module):
|
166 |
+
'''
|
167 |
+
Conv2d + BN layer with folding capability to speed up inference
|
168 |
+
Can be merged with Conv() function with additional arguments
|
169 |
+
'''
|
170 |
+
def __init__(self, a, b, kernel_size=1, stride=1, padding=0, dilation=1, groups=1, bn_weight_init=1, bias=False):
|
171 |
+
super().__init__()
|
172 |
+
self.conv = torch.nn.Conv2d(a, b, kernel_size, stride, padding, dilation, groups, bias=False)
|
173 |
+
if 1:
|
174 |
+
self.bn = torch.nn.BatchNorm2d(b)
|
175 |
+
torch.nn.init.constant_(self.bn.weight, bn_weight_init)
|
176 |
+
torch.nn.init.constant_(self.bn.bias, 0)
|
177 |
+
|
178 |
+
def forward(self,x):
|
179 |
+
x = self.conv(x)
|
180 |
+
x = self.bn(x)
|
181 |
+
return x
|
182 |
+
|
183 |
+
@torch.no_grad()
|
184 |
+
def switch_to_deploy(self):
|
185 |
+
if not isinstance(self.bn, nn.Identity):
|
186 |
+
c, bn = self.conv, self.bn
|
187 |
+
w = bn.weight / (bn.running_var + bn.eps) ** 0.5
|
188 |
+
w = c.weight * w[:, None, None, None]
|
189 |
+
b = bn.bias - bn.running_mean * bn.weight / \
|
190 |
+
(bn.running_var + bn.eps)**0.5
|
191 |
+
self.conv.weight.data.copy_(w)
|
192 |
+
self.conv.bias = nn.Parameter(b)
|
193 |
+
self.bn = nn.Identity()
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
def window_reverse(windows, window_size, H, W, pad_hw):
|
198 |
+
"""
|
199 |
+
Windows to the full feature map
|
200 |
+
Args:
|
201 |
+
windows: local window features (num_windows*B, window_size, window_size, C)
|
202 |
+
window_size: Window size
|
203 |
+
H: Height of image
|
204 |
+
W: Width of image
|
205 |
+
pad_w - a tuple of image passing used in windowing step
|
206 |
+
Returns:
|
207 |
+
x: (B, C, H, W)
|
208 |
+
|
209 |
+
"""
|
210 |
+
# print(f"window_reverse, windows.shape {windows.shape}")
|
211 |
+
Hp, Wp = pad_hw
|
212 |
+
if window_size == 0 or (window_size==H and window_size==W):
|
213 |
+
B = int(windows.shape[0] / (Hp * Wp / window_size / window_size))
|
214 |
+
x = windows.transpose(1, 2).view(B, -1, H, W)
|
215 |
+
else:
|
216 |
+
B = int(windows.shape[0] / (Hp * Wp / window_size / window_size))
|
217 |
+
x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
|
218 |
+
x = x.permute(0, 5, 1, 3, 2, 4).reshape(B,windows.shape[2], Hp, Wp)
|
219 |
+
|
220 |
+
if Hp > H or Wp > W:
|
221 |
+
x = x[:, :, :H, :W, ].contiguous()
|
222 |
+
|
223 |
+
return x
|
224 |
+
|
225 |
+
|
226 |
+
|
227 |
+
class PosEmbMLPSwinv2D(nn.Module):
|
228 |
+
"""
|
229 |
+
2D positional embedding from Swin Transformer v2
|
230 |
+
Added functionality to store the positional embedding in the model and not recompute it every time
|
231 |
+
"""
|
232 |
+
def __init__(
|
233 |
+
self, window_size, pretrained_window_size, num_heads, seq_length, no_log=False, cpb_mlp_hidden=512,
|
234 |
+
):
|
235 |
+
super().__init__()
|
236 |
+
self.window_size = window_size
|
237 |
+
self.num_heads = num_heads
|
238 |
+
# mlp to generate continuous relative position bias
|
239 |
+
self.cpb_mlp = nn.Sequential(
|
240 |
+
nn.Linear(2, cpb_mlp_hidden, bias=True),
|
241 |
+
nn.ReLU(inplace=True),
|
242 |
+
nn.Linear(cpb_mlp_hidden, num_heads, bias=False),
|
243 |
+
)
|
244 |
+
|
245 |
+
self.grid_exists = False
|
246 |
+
self.seq_length = seq_length
|
247 |
+
self.deploy = False
|
248 |
+
self.num_heads = num_heads
|
249 |
+
self.no_log = no_log
|
250 |
+
self.pretrained_window_size = pretrained_window_size
|
251 |
+
self.relative_bias_window_size = window_size
|
252 |
+
|
253 |
+
relative_coords_table, relative_position_index, relative_bias = self.relative_bias_initialization(window_size, num_heads,
|
254 |
+
pretrained_window_size, seq_length,
|
255 |
+
no_log)
|
256 |
+
|
257 |
+
self.register_buffer("relative_coords_table", relative_coords_table)
|
258 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
259 |
+
self.register_buffer("relative_bias", relative_bias) # for EMA
|
260 |
+
|
261 |
+
def relative_bias_initialization(self, window_size, num_heads, pretrained_window_size, seq_length, no_log):
|
262 |
+
# as in separate function to support window size chage after model weights loading
|
263 |
+
relative_coords_h = torch.arange(
|
264 |
+
-(window_size[0] - 1), window_size[0], dtype=torch.float32
|
265 |
+
)
|
266 |
+
relative_coords_w = torch.arange(
|
267 |
+
-(window_size[1] - 1), window_size[1], dtype=torch.float32
|
268 |
+
)
|
269 |
+
relative_coords_table = (
|
270 |
+
torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w]))
|
271 |
+
.permute(1, 2, 0)
|
272 |
+
.contiguous()
|
273 |
+
.unsqueeze(0)
|
274 |
+
) # 1, 2*Wh-1, 2*Ww-1, 2
|
275 |
+
if pretrained_window_size[0] > 0:
|
276 |
+
relative_coords_table[:, :, :, 0] /= pretrained_window_size[0] - 1
|
277 |
+
relative_coords_table[:, :, :, 1] /= pretrained_window_size[1] - 1
|
278 |
+
else:
|
279 |
+
relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1
|
280 |
+
relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1
|
281 |
+
|
282 |
+
if not no_log:
|
283 |
+
relative_coords_table *= 8 # normalize to -8, 8
|
284 |
+
relative_coords_table = (
|
285 |
+
torch.sign(relative_coords_table)
|
286 |
+
* torch.log2(torch.abs(relative_coords_table) + 1.0)
|
287 |
+
/ np.log2(8)
|
288 |
+
)
|
289 |
+
|
290 |
+
# get pair-wise relative position index for each token inside the window
|
291 |
+
coords_h = torch.arange(self.window_size[0])
|
292 |
+
coords_w = torch.arange(self.window_size[1])
|
293 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
294 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
295 |
+
relative_coords = (
|
296 |
+
coords_flatten[:, :, None] - coords_flatten[:, None, :]
|
297 |
+
) # 2, Wh*Ww, Wh*Ww
|
298 |
+
relative_coords = relative_coords.permute(
|
299 |
+
1, 2, 0
|
300 |
+
).contiguous() # Wh*Ww, Wh*Ww, 2
|
301 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
302 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
303 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
304 |
+
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
305 |
+
|
306 |
+
relative_bias = torch.zeros(1, num_heads, seq_length, seq_length)
|
307 |
+
|
308 |
+
self.relative_bias_window_size = window_size
|
309 |
+
|
310 |
+
return relative_coords_table, relative_position_index, relative_bias
|
311 |
+
|
312 |
+
|
313 |
+
def switch_to_deploy(self):
|
314 |
+
self.deploy = True
|
315 |
+
self.grid_exists = True
|
316 |
+
|
317 |
+
def forward(self, input_tensor):
|
318 |
+
# for efficiency, we want this forward to be folded into a single operation (sum)
|
319 |
+
# if resolution stays the same, then we dont need to recompute MLP layers
|
320 |
+
|
321 |
+
if not self.deploy or self.training:
|
322 |
+
self.grid_exists = False
|
323 |
+
|
324 |
+
#compare if all elements in self.window_size list match those in self.relative_bias_window_size
|
325 |
+
if not all([self.window_size[i] == self.relative_bias_window_size[i] for i in range(len(self.window_size))]):
|
326 |
+
relative_coords_table, relative_position_index, relative_bias = self.relative_bias_initialization(self.window_size, self.num_heads,
|
327 |
+
self.pretrained_window_size, self.seq_length,
|
328 |
+
self.no_log)
|
329 |
+
|
330 |
+
self.relative_coords_table = relative_coords_table.to(self.relative_coords_table.device)
|
331 |
+
self.relative_position_index = relative_position_index.to(self.relative_position_index.device)
|
332 |
+
self.relative_bias = relative_bias.to(self.relative_bias.device)
|
333 |
+
|
334 |
+
if self.deploy and self.grid_exists:
|
335 |
+
input_tensor = input_tensor + self.relative_bias
|
336 |
+
return input_tensor
|
337 |
+
|
338 |
+
if 1:
|
339 |
+
self.grid_exists = True
|
340 |
+
|
341 |
+
relative_position_bias_table = self.cpb_mlp(
|
342 |
+
self.relative_coords_table
|
343 |
+
).view(-1, self.num_heads)
|
344 |
+
relative_position_bias = relative_position_bias_table[
|
345 |
+
self.relative_position_index.view(-1)
|
346 |
+
].view(
|
347 |
+
self.window_size[0] * self.window_size[1],
|
348 |
+
self.window_size[0] * self.window_size[1],
|
349 |
+
-1,
|
350 |
+
) # Wh*Ww,Wh*Ww,nH
|
351 |
+
|
352 |
+
relative_position_bias = relative_position_bias.permute(
|
353 |
+
2, 0, 1
|
354 |
+
).contiguous() # nH, Wh*Ww, Wh*Ww
|
355 |
+
relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
|
356 |
+
|
357 |
+
self.relative_bias = relative_position_bias.unsqueeze(0)
|
358 |
+
|
359 |
+
input_tensor = input_tensor + self.relative_bias
|
360 |
+
return input_tensor
|
361 |
+
|
362 |
+
|
363 |
+
class GRAAttentionBlock(nn.Module):
|
364 |
+
def __init__(self, window_size, dim_in, dim_out,
|
365 |
+
num_heads, drop_path=0., qk_scale=None, qkv_bias=False,
|
366 |
+
norm_layer=nn.LayerNorm, layer_scale=None,
|
367 |
+
use_swiglu=True,
|
368 |
+
subsample_ratio=1, dim_ratio=1, conv_base=False,
|
369 |
+
do_windowing=True, multi_query=False, use_shift=0,
|
370 |
+
cpb_mlp_hidden=512, conv_groups_ratio=0):
|
371 |
+
'''
|
372 |
+
Global Resolution Attention Block , see README for details
|
373 |
+
Attention with subsampling to get a bigger receptive field for attention
|
374 |
+
conv_base - use conv2d instead of avgpool2d for downsample / upsample
|
375 |
+
|
376 |
+
|
377 |
+
'''
|
378 |
+
super().__init__()
|
379 |
+
|
380 |
+
self.shift_size=window_size//2 if use_shift else 0
|
381 |
+
|
382 |
+
self.do_windowing = do_windowing
|
383 |
+
self.subsample_ratio = subsample_ratio
|
384 |
+
|
385 |
+
|
386 |
+
|
387 |
+
if do_windowing:
|
388 |
+
if conv_base:
|
389 |
+
self.downsample_op = nn.Conv2d(dim_in, dim_out, kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity()
|
390 |
+
|
391 |
+
|
392 |
+
self.downsample_mixer = nn.Identity()
|
393 |
+
self.upsample_mixer = nn.Identity()
|
394 |
+
self.upsample_op = nn.ConvTranspose2d(dim_in, dim_out, kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity()
|
395 |
+
else:
|
396 |
+
self.downsample_op = nn.AvgPool2d(kernel_size=subsample_ratio, stride=subsample_ratio) if subsample_ratio > 1 else nn.Identity()
|
397 |
+
self.downsample_mixer = Conv2d_BN(dim_in, dim_out, kernel_size=1, stride=1) if subsample_ratio > 1 else nn.Identity()
|
398 |
+
self.upsample_mixer = nn.Upsample(scale_factor=subsample_ratio, mode='nearest') if subsample_ratio > 1 else nn.Identity()
|
399 |
+
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()
|
400 |
+
|
401 |
+
|
402 |
+
# in case there is no downsampling conv we want to have it separately
|
403 |
+
# will help with information propagation between windows
|
404 |
+
if subsample_ratio == 1:
|
405 |
+
# conv_groups_ratio=0
|
406 |
+
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)
|
407 |
+
# 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)
|
408 |
+
# self.pre_conv_act = nn.ReLU6()
|
409 |
+
#for simplicity:
|
410 |
+
self.pre_conv_act = nn.Identity()
|
411 |
+
if conv_groups_ratio == -1:
|
412 |
+
self.pre_conv = nn.Identity()
|
413 |
+
self.pre_conv_act = nn.Identity()
|
414 |
+
|
415 |
+
self.window_size = window_size
|
416 |
+
|
417 |
+
self.norm1 = norm_layer(dim_in)
|
418 |
+
|
419 |
+
self.attn = WindowAttention(
|
420 |
+
dim_in,
|
421 |
+
num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
422 |
+
resolution=window_size,
|
423 |
+
seq_length=window_size**2, dim_out=dim_in, multi_query=multi_query,
|
424 |
+
shift_size=self.shift_size, cpb_mlp_hidden=cpb_mlp_hidden)
|
425 |
+
|
426 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
427 |
+
|
428 |
+
use_layer_scale = layer_scale is not None and type(layer_scale) in [int, float]
|
429 |
+
self.gamma1 = nn.Parameter(layer_scale * torch.ones(dim_in)) if use_layer_scale else 1
|
430 |
+
|
431 |
+
### mlp layer
|
432 |
+
mlp_ratio = 4
|
433 |
+
self.norm2 = norm_layer(dim_in)
|
434 |
+
mlp_hidden_dim = int(dim_in * mlp_ratio)
|
435 |
+
|
436 |
+
activation = nn.GELU if not use_swiglu else SwiGLU
|
437 |
+
mlp_hidden_dim = int((4 * dim_in * 1 / 2) / 64) * 64 if use_swiglu else mlp_hidden_dim
|
438 |
+
|
439 |
+
self.mlp = Mlp(in_features=dim_in, hidden_features=mlp_hidden_dim, act_layer=activation, use_swiglu=use_swiglu)
|
440 |
+
|
441 |
+
self.gamma2 = nn.Parameter(layer_scale * torch.ones(dim_in)) if layer_scale else 1
|
442 |
+
self.drop_path2=DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
443 |
+
|
444 |
+
|
445 |
+
def forward(self, x):
|
446 |
+
skip_connection = x
|
447 |
+
attn_mask = None
|
448 |
+
|
449 |
+
# in case there is no downsampling conv we want to have it separately
|
450 |
+
# will help with information propagation
|
451 |
+
if self.subsample_ratio == 1:
|
452 |
+
x = self.pre_conv_act(self.pre_conv(x)) + skip_connection
|
453 |
+
|
454 |
+
if self.do_windowing:
|
455 |
+
# performing windowing if required
|
456 |
+
x = self.downsample_op(x)
|
457 |
+
x = self.downsample_mixer(x)
|
458 |
+
|
459 |
+
if self.window_size>0:
|
460 |
+
H, W = x.shape[2], x.shape[3]
|
461 |
+
|
462 |
+
if self.shift_size > 0 and H>self.window_size and W>self.window_size:
|
463 |
+
# @swin like cyclic shift, doesnt show better performance
|
464 |
+
x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(2, 3))
|
465 |
+
|
466 |
+
x, pad_hw = window_partition(x, self.window_size)
|
467 |
+
|
468 |
+
if self.shift_size > 0 and H>self.window_size and W>self.window_size:
|
469 |
+
# set atten matrix to have -100 and the top right square
|
470 |
+
# attn[:, :, :-self.shift_size, -self.shift_size:] = -100.0
|
471 |
+
# calculate attention mask for SW-MSA
|
472 |
+
# not used in final version, can be useful for some cases especially for high res
|
473 |
+
H, W = pad_hw
|
474 |
+
img_mask = torch.zeros((1, H, W, 1), device=x.device) # 1 H W 1
|
475 |
+
h_slices = (slice(0, -self.window_size),
|
476 |
+
slice(-self.window_size, -self.shift_size),
|
477 |
+
slice(-self.shift_size, None))
|
478 |
+
w_slices = (slice(0, -self.window_size),
|
479 |
+
slice(-self.window_size, -self.shift_size),
|
480 |
+
slice(-self.shift_size, None))
|
481 |
+
cnt = 0
|
482 |
+
for h in h_slices:
|
483 |
+
for w in w_slices:
|
484 |
+
img_mask[:, h, w, :] = cnt
|
485 |
+
cnt += 1
|
486 |
+
img_mask = img_mask.transpose(1,2).transpose(1,3)
|
487 |
+
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
488 |
+
|
489 |
+
mask_windows = mask_windows[0].view(-1, self.window_size * self.window_size)
|
490 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
491 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
492 |
+
|
493 |
+
# window attention
|
494 |
+
x = x + self.drop_path1(self.gamma1*self.attn(self.norm1(x), attn_mask=attn_mask)) # or pass H,W
|
495 |
+
# mlp layer
|
496 |
+
x = x + self.drop_path2(self.gamma2*self.mlp(self.norm2(x)))
|
497 |
+
|
498 |
+
if self.do_windowing:
|
499 |
+
if self.window_size > 0:
|
500 |
+
x = window_reverse(x, self.window_size, H, W, pad_hw)
|
501 |
+
|
502 |
+
# reverse cyclic shift
|
503 |
+
if self.shift_size > 0 and H>self.window_size and W>self.window_size:
|
504 |
+
# @swin like cyclic shift, not tested
|
505 |
+
x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(2, 3))
|
506 |
+
|
507 |
+
x = self.upsample_mixer(x)
|
508 |
+
x = self.upsample_op(x)
|
509 |
+
|
510 |
+
|
511 |
+
if x.shape[2] != skip_connection.shape[2] or x.shape[3] != skip_connection.shape[3]:
|
512 |
+
x = torch.nn.functional.pad(x, ( 0, -x.shape[3] + skip_connection.shape[3], 0, -x.shape[2] + skip_connection.shape[2]), mode="reflect")
|
513 |
+
# need to add skip connection because downsampling and upsampling will break residual connection
|
514 |
+
# 0.5 is needed to make sure that the skip connection is not too strong
|
515 |
+
# in case of no downsample / upsample we can show that 0.5 compensates for the residual connection
|
516 |
+
x = 0.5 * x + 0.5 * skip_connection
|
517 |
+
return x
|
518 |
+
|
519 |
+
|
520 |
+
|
521 |
+
|
522 |
+
class MultiResolutionAttention(nn.Module):
|
523 |
+
"""
|
524 |
+
MultiResolutionAttention (MRA) module
|
525 |
+
The idea is to use multiple attention blocks with different resolution
|
526 |
+
Feature maps are downsampled / upsampled for each attention block on different blocks
|
527 |
+
Every attention block supports windowing
|
528 |
+
"""
|
529 |
+
|
530 |
+
def __init__(self, window_size, sr_ratio,
|
531 |
+
dim, dim_ratio, num_heads,
|
532 |
+
do_windowing=True,
|
533 |
+
layer_scale=1e-5, norm_layer=nn.LayerNorm,
|
534 |
+
drop_path = 0, qkv_bias=False, qk_scale=1.0,
|
535 |
+
use_swiglu=True, multi_query=False, conv_base=False,
|
536 |
+
use_shift=0, cpb_mlp_hidden=512, conv_groups_ratio=0) -> None:
|
537 |
+
"""
|
538 |
+
Args:
|
539 |
+
input_resolution: input image resolution
|
540 |
+
window_size: window size
|
541 |
+
compression_ratio: compression ratio
|
542 |
+
max_depth: maximum depth of the GRA module
|
543 |
+
use_shift: do window shifting
|
544 |
+
"""
|
545 |
+
super().__init__()
|
546 |
+
|
547 |
+
depth = len(sr_ratio)
|
548 |
+
|
549 |
+
self.attention_blocks = nn.ModuleList()
|
550 |
+
|
551 |
+
|
552 |
+
for i in range(depth):
|
553 |
+
subsample_ratio = sr_ratio[i]
|
554 |
+
if len(window_size) > i:
|
555 |
+
window_size_local = window_size[i]
|
556 |
+
else:
|
557 |
+
window_size_local = window_size[0]
|
558 |
+
|
559 |
+
self.attention_blocks.append(GRAAttentionBlock(window_size=window_size_local,
|
560 |
+
dim_in=dim, dim_out=dim, num_heads=num_heads,
|
561 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale, norm_layer=norm_layer,
|
562 |
+
layer_scale=layer_scale, drop_path=drop_path,
|
563 |
+
use_swiglu=use_swiglu, subsample_ratio=subsample_ratio, dim_ratio=dim_ratio,
|
564 |
+
do_windowing=do_windowing, multi_query=multi_query, conv_base=conv_base,
|
565 |
+
use_shift=use_shift, cpb_mlp_hidden=cpb_mlp_hidden, conv_groups_ratio=conv_groups_ratio),
|
566 |
+
)
|
567 |
+
|
568 |
+
def forward(self, x):
|
569 |
+
|
570 |
+
for attention_block in self.attention_blocks:
|
571 |
+
x = attention_block(x)
|
572 |
+
|
573 |
+
return x
|
574 |
+
|
575 |
+
|
576 |
+
|
577 |
+
class Mlp(nn.Module):
|
578 |
+
"""
|
579 |
+
Multi-Layer Perceptron (MLP) block
|
580 |
+
"""
|
581 |
+
|
582 |
+
def __init__(self,
|
583 |
+
in_features,
|
584 |
+
hidden_features=None,
|
585 |
+
out_features=None,
|
586 |
+
act_layer=nn.GELU,
|
587 |
+
use_swiglu=True,
|
588 |
+
drop=0.):
|
589 |
+
"""
|
590 |
+
Args:
|
591 |
+
in_features: input features dimension.
|
592 |
+
hidden_features: hidden features dimension.
|
593 |
+
out_features: output features dimension.
|
594 |
+
act_layer: activation function.
|
595 |
+
drop: dropout rate.
|
596 |
+
"""
|
597 |
+
|
598 |
+
super().__init__()
|
599 |
+
out_features = out_features or in_features
|
600 |
+
hidden_features = hidden_features or in_features
|
601 |
+
self.fc1 = nn.Linear(in_features, hidden_features * (2 if use_swiglu else 1), bias=False)
|
602 |
+
self.act = act_layer()
|
603 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=False)
|
604 |
+
|
605 |
+
def forward(self, x):
|
606 |
+
x_size = x.size()
|
607 |
+
x = x.view(-1, x_size[-1])
|
608 |
+
x = self.fc1(x)
|
609 |
+
x = self.act(x)
|
610 |
+
x = self.fc2(x)
|
611 |
+
x = x.view(x_size)
|
612 |
+
return x
|
613 |
+
|
614 |
+
class Downsample(nn.Module):
|
615 |
+
"""
|
616 |
+
Down-sampling block
|
617 |
+
Pixel Unshuffle is used for down-sampling, works great accuracy - wise but takes 10% more TRT time
|
618 |
+
"""
|
619 |
+
|
620 |
+
def __init__(self,
|
621 |
+
dim,
|
622 |
+
shuffle = False,
|
623 |
+
):
|
624 |
+
"""
|
625 |
+
Args:
|
626 |
+
dim: feature size dimension.
|
627 |
+
shuffle: idea with
|
628 |
+
keep_dim: bool argument for maintaining the resolution.
|
629 |
+
"""
|
630 |
+
|
631 |
+
super().__init__()
|
632 |
+
dim_out = 2 * dim
|
633 |
+
|
634 |
+
if shuffle:
|
635 |
+
self.norm = lambda x: pixel_unshuffle(x, factor=2)
|
636 |
+
self.reduction = Conv2d_BN(dim*4, dim_out, 1, 1, 0, bias=False)
|
637 |
+
# pixel unshuffleging works well but doesnt provide any speedup
|
638 |
+
else:
|
639 |
+
# removed layer norm for better, in this formulation we are getting 10% better speed
|
640 |
+
# LayerNorm for high resolution inputs will be a pain as it pools over the entire spatial dimension
|
641 |
+
# therefore we remove it compared to the original implementation in FasterViTv1
|
642 |
+
self.norm = nn.Identity()
|
643 |
+
self.reduction = Conv2d_BN(dim, dim_out, 3, 2, 1, bias=False)
|
644 |
+
|
645 |
+
|
646 |
+
def forward(self, x):
|
647 |
+
x = self.norm(x)
|
648 |
+
x = self.reduction(x)
|
649 |
+
return x
|
650 |
+
|
651 |
+
|
652 |
+
class PatchEmbed(nn.Module):
|
653 |
+
"""
|
654 |
+
Patch embedding block
|
655 |
+
Used to convert image into an initial set of feature maps with lower resolution
|
656 |
+
"""
|
657 |
+
|
658 |
+
def __init__(self, in_chans=3, in_dim=64, dim=96, shuffle_down=False):
|
659 |
+
"""
|
660 |
+
Args:
|
661 |
+
in_chans: number of input channels.
|
662 |
+
in_dim: intermediate feature size dimension to speed up stem.
|
663 |
+
dim: final stem channel number
|
664 |
+
shuffle_down: use PixelUnshuffle for down-sampling, effectively increases the receptive field
|
665 |
+
"""
|
666 |
+
|
667 |
+
super().__init__()
|
668 |
+
# shuffle_down = False
|
669 |
+
if not shuffle_down:
|
670 |
+
self.proj = nn.Identity()
|
671 |
+
self.conv_down = nn.Sequential(
|
672 |
+
Conv2d_BN(in_chans, in_dim, 3, 2, 1, bias=False),
|
673 |
+
nn.ReLU(),
|
674 |
+
Conv2d_BN(in_dim, dim, 3, 2, 1, bias=False),
|
675 |
+
nn.ReLU()
|
676 |
+
)
|
677 |
+
else:
|
678 |
+
self.proj = lambda x: pixel_unshuffle(x, factor=4)
|
679 |
+
self.conv_down = nn.Sequential(Conv2d_BN(in_chans*16, dim, 3, 1, 1),
|
680 |
+
nn.ReLU(),
|
681 |
+
)
|
682 |
+
|
683 |
+
def forward(self, x):
|
684 |
+
x = self.proj(x)
|
685 |
+
x = self.conv_down(x)
|
686 |
+
return x
|
687 |
+
|
688 |
+
|
689 |
+
|
690 |
+
class ConvBlock(nn.Module):
|
691 |
+
"""
|
692 |
+
Convolutional block, used in first couple of stages
|
693 |
+
Experimented with plan resnet-18 like modules, they are the best in terms of throughput
|
694 |
+
Finally, YOLOv8 idea seem to work fine (resnet-18 like block with squeezed feature dimension, and feature concatendation at the end)
|
695 |
+
"""
|
696 |
+
def __init__(self, dim,
|
697 |
+
drop_path=0.,
|
698 |
+
layer_scale=None,
|
699 |
+
kernel_size=3,
|
700 |
+
):
|
701 |
+
super().__init__()
|
702 |
+
|
703 |
+
self.conv1 = Conv2d_BN(dim, dim, kernel_size=kernel_size, stride=1, padding=1)
|
704 |
+
self.act1 = nn.GELU()
|
705 |
+
|
706 |
+
self.conv2 = Conv2d_BN(dim, dim, kernel_size=kernel_size, stride=1, padding=1)
|
707 |
+
|
708 |
+
self.layer_scale = layer_scale
|
709 |
+
if layer_scale is not None and type(layer_scale) in [int, float]:
|
710 |
+
self.gamma = nn.Parameter(layer_scale * torch.ones(dim))
|
711 |
+
self.layer_scale = True
|
712 |
+
else:
|
713 |
+
self.layer_scale = False
|
714 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
715 |
+
|
716 |
+
def forward(self, x):
|
717 |
+
input = x
|
718 |
+
|
719 |
+
x = self.conv1(x)
|
720 |
+
x = self.act1(x)
|
721 |
+
x = self.conv2(x)
|
722 |
+
|
723 |
+
if self.layer_scale:
|
724 |
+
x = x * self.gamma.view(1, -1, 1, 1)
|
725 |
+
x = input + self.drop_path(x)
|
726 |
+
return x
|
727 |
+
|
728 |
+
|
729 |
+
class WindowAttention(nn.Module):
|
730 |
+
# Windowed Attention from SwinV2
|
731 |
+
# use a MLP trick to deal with various input image resolutions, then fold it to improve speed
|
732 |
+
|
733 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, resolution=0,
|
734 |
+
seq_length=0, dim_out=None, multi_query=False, shift_size=0, cpb_mlp_hidden=512):
|
735 |
+
# taken from EdgeViT and tweaked with attention bias.
|
736 |
+
super().__init__()
|
737 |
+
if not dim_out: dim_out = dim
|
738 |
+
self.shift_size = shift_size
|
739 |
+
self.multi_query = multi_query
|
740 |
+
self.num_heads = num_heads
|
741 |
+
head_dim = dim // num_heads
|
742 |
+
self.head_dim = dim // num_heads
|
743 |
+
|
744 |
+
self.dim_internal = dim
|
745 |
+
|
746 |
+
self.scale = qk_scale or head_dim ** -0.5
|
747 |
+
if not multi_query:
|
748 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
749 |
+
else:
|
750 |
+
self.qkv = nn.Linear(dim, dim + 2*self.head_dim, bias=qkv_bias)
|
751 |
+
|
752 |
+
self.proj = nn.Linear(dim, dim_out, bias=False)
|
753 |
+
# attention positional bias
|
754 |
+
self.pos_emb_funct = PosEmbMLPSwinv2D(window_size=[resolution, resolution],
|
755 |
+
pretrained_window_size=[resolution, resolution],
|
756 |
+
num_heads=num_heads,
|
757 |
+
seq_length=seq_length,
|
758 |
+
cpb_mlp_hidden=cpb_mlp_hidden)
|
759 |
+
|
760 |
+
self.resolution = resolution
|
761 |
+
|
762 |
+
def forward(self, x, attn_mask = None):
|
763 |
+
B, N, C = x.shape
|
764 |
+
|
765 |
+
if not self.multi_query:
|
766 |
+
qkv = self.qkv(x).reshape(B, -1, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
767 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
768 |
+
else:
|
769 |
+
qkv = self.qkv(x)
|
770 |
+
(q, k, v) = qkv.split([self.dim_internal, self.head_dim, self.head_dim], dim=2)
|
771 |
+
|
772 |
+
q = q.reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
|
773 |
+
k = k.reshape(B, -1, 1, C // self.num_heads).permute(0, 2, 1, 3)
|
774 |
+
v = v.reshape(B, -1, 1, C // self.num_heads).permute(0, 2, 1, 3)
|
775 |
+
|
776 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
777 |
+
|
778 |
+
attn = self.pos_emb_funct(attn)
|
779 |
+
|
780 |
+
#add window shift
|
781 |
+
if attn_mask is not None:
|
782 |
+
nW = attn_mask.shape[0]
|
783 |
+
attn = attn.view(B // nW, nW, self.num_heads, N, N) + attn_mask.unsqueeze(1).unsqueeze(0)
|
784 |
+
attn = attn.view(-1, self.num_heads, N, N)
|
785 |
+
|
786 |
+
attn = attn.softmax(dim=-1)
|
787 |
+
x = (attn @ v).transpose(1, 2).reshape(B, -1, C)
|
788 |
+
x = self.proj(x)
|
789 |
+
return x
|
790 |
+
|
791 |
+
|
792 |
+
|
793 |
+
class FasterViTLayer(nn.Module):
|
794 |
+
"""
|
795 |
+
fastervitlayer
|
796 |
+
"""
|
797 |
+
|
798 |
+
def __init__(self,
|
799 |
+
dim,
|
800 |
+
depth,
|
801 |
+
num_heads,
|
802 |
+
window_size,
|
803 |
+
conv=False,
|
804 |
+
downsample=True,
|
805 |
+
mlp_ratio=4.,
|
806 |
+
qkv_bias=False,
|
807 |
+
qk_scale=None,
|
808 |
+
norm_layer=nn.LayerNorm,
|
809 |
+
drop_path=0.,
|
810 |
+
layer_scale=None,
|
811 |
+
layer_scale_conv=None,
|
812 |
+
sr_dim_ratio=1,
|
813 |
+
sr_ratio=1,
|
814 |
+
multi_query=False,
|
815 |
+
use_swiglu=True,
|
816 |
+
yolo_arch=False,
|
817 |
+
downsample_shuffle=False,
|
818 |
+
conv_base=False,
|
819 |
+
use_shift=False,
|
820 |
+
cpb_mlp_hidden=512,
|
821 |
+
conv_groups_ratio=0,
|
822 |
+
verbose: bool = True,
|
823 |
+
|
824 |
+
):
|
825 |
+
"""
|
826 |
+
Args:
|
827 |
+
dim: feature size dimension.
|
828 |
+
depth: number of layers in each stage.
|
829 |
+
input_resolution: input image resolution.
|
830 |
+
window_size: window size in each stage.
|
831 |
+
downsample: bool argument for down-sampling.
|
832 |
+
mlp_ratio: MLP ratio.
|
833 |
+
num_heads: number of heads in each stage.
|
834 |
+
qkv_bias: bool argument for query, key, value learnable bias.
|
835 |
+
qk_scale: bool argument to scaling query, key.
|
836 |
+
drop: dropout rate.
|
837 |
+
attn_drop: attention dropout rate.
|
838 |
+
drop_path: drop path rate.
|
839 |
+
norm_layer: normalization layer.
|
840 |
+
layer_scale: layer scaling coefficient.
|
841 |
+
use_shift: SWIN like window shifting for half the window size for every alternating layer (considering multi-resolution)
|
842 |
+
conv_groups_ratio: group ratio for conv when no subsampling in multi-res attention
|
843 |
+
"""
|
844 |
+
|
845 |
+
super().__init__()
|
846 |
+
self.conv = conv
|
847 |
+
self.yolo_arch=False
|
848 |
+
self.verbose = verbose
|
849 |
+
if conv:
|
850 |
+
if not yolo_arch:
|
851 |
+
self.blocks = nn.ModuleList([
|
852 |
+
ConvBlock(dim=dim,
|
853 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
854 |
+
layer_scale=layer_scale_conv)
|
855 |
+
for i in range(depth)])
|
856 |
+
self.blocks = nn.Sequential(*self.blocks)
|
857 |
+
else:
|
858 |
+
self.blocks = C2f(dim,dim,n=depth,shortcut=True,e=0.5)
|
859 |
+
self.yolo_arch=True
|
860 |
+
else:
|
861 |
+
if not isinstance(window_size, list): window_size = [window_size]
|
862 |
+
self.window_size = window_size[0]
|
863 |
+
self.do_single_windowing = True
|
864 |
+
if not isinstance(sr_ratio, list): sr_ratio = [sr_ratio]
|
865 |
+
self.sr_ratio = sr_ratio
|
866 |
+
if any([sr!=1 for sr in sr_ratio]) or len(set(window_size))>1:
|
867 |
+
self.do_single_windowing = False
|
868 |
+
do_windowing = True
|
869 |
+
else:
|
870 |
+
self.do_single_windowing = True
|
871 |
+
do_windowing = False
|
872 |
+
|
873 |
+
#for v2_2
|
874 |
+
if conv_groups_ratio != -1:
|
875 |
+
self.do_single_windowing = False
|
876 |
+
do_windowing = True
|
877 |
+
|
878 |
+
self.blocks = nn.ModuleList()
|
879 |
+
for i in range(depth):
|
880 |
+
self.blocks.append(
|
881 |
+
MultiResolutionAttention(window_size=window_size,
|
882 |
+
sr_ratio=sr_ratio,
|
883 |
+
dim=dim,
|
884 |
+
dim_ratio = sr_dim_ratio,
|
885 |
+
num_heads=num_heads,
|
886 |
+
norm_layer=norm_layer,
|
887 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
888 |
+
layer_scale=layer_scale,
|
889 |
+
qkv_bias=qkv_bias,
|
890 |
+
qk_scale=qk_scale,
|
891 |
+
use_swiglu=use_swiglu,
|
892 |
+
do_windowing=do_windowing,
|
893 |
+
multi_query=multi_query,
|
894 |
+
conv_base=conv_base,
|
895 |
+
cpb_mlp_hidden=cpb_mlp_hidden,
|
896 |
+
use_shift =0 if ((not use_shift) or ((i) % 2 == 0)) else True ,
|
897 |
+
conv_groups_ratio=conv_groups_ratio,
|
898 |
+
))
|
899 |
+
self.blocks = nn.Sequential(*self.blocks)
|
900 |
+
|
901 |
+
self.transformer = not conv
|
902 |
+
self.downsample = None if not downsample else Downsample(dim=dim, shuffle=downsample_shuffle)
|
903 |
+
|
904 |
+
|
905 |
+
def forward(self, x):
|
906 |
+
B, C, H, W = x.shape
|
907 |
+
|
908 |
+
# do padding for transforemr
|
909 |
+
interpolate = True
|
910 |
+
if self.transformer and interpolate:
|
911 |
+
# Windowed Attention will split feature map into windows with the size of window_size x window_size
|
912 |
+
# if the resolution is not divisible by window_size, we need to interpolate the feature map
|
913 |
+
# can be done via padding, but doing so after training hurts the model performance.
|
914 |
+
# interpolation affects the performance as well, but not as much as padding
|
915 |
+
if isinstance(self.window_size, list) or isinstance(self.window_size, tuple):
|
916 |
+
current_max_window_size = max(self.window_size)
|
917 |
+
else:
|
918 |
+
current_max_window_size = self.window_size
|
919 |
+
|
920 |
+
max_window_size = max([res_upsample*current_max_window_size for res_upsample in self.sr_ratio])
|
921 |
+
if H % max_window_size != 0 or W % max_window_size != 0:
|
922 |
+
new_h = int(np.ceil(H/max_window_size)*max_window_size)
|
923 |
+
new_w = int(np.ceil(W/max_window_size)*max_window_size)
|
924 |
+
x = F.interpolate(x, size=(new_h, new_w), mode='nearest')
|
925 |
+
if self.verbose:
|
926 |
+
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}.")
|
927 |
+
|
928 |
+
|
929 |
+
if self.transformer and self.do_single_windowing:
|
930 |
+
H, W = x.shape[2], x.shape[3]
|
931 |
+
x, pad_hw = window_partition(x, self.window_size)
|
932 |
+
|
933 |
+
#run main blocks
|
934 |
+
x = self.blocks(x)
|
935 |
+
|
936 |
+
if self.transformer and self.do_single_windowing:
|
937 |
+
x = window_reverse(x, self.window_size, H, W, pad_hw)
|
938 |
+
|
939 |
+
if self.transformer and interpolate:
|
940 |
+
#lets keep original resolution, might be not ideal, but for the upsampling tower we need to keep the expected resolution.
|
941 |
+
x = F.interpolate(x, size=(H, W), mode='nearest')
|
942 |
+
|
943 |
+
if self.downsample is None:
|
944 |
+
return x, x
|
945 |
+
|
946 |
+
return self.downsample(x), x # changing to output pre downsampled features
|
947 |
+
|
948 |
+
|
949 |
+
class InterpolateLayer(nn.Module):
|
950 |
+
def __init__(self, size=None, scale_factor=None, mode='nearest'):
|
951 |
+
super(InterpolateLayer, self).__init__()
|
952 |
+
self.size = size
|
953 |
+
self.scale_factor = scale_factor
|
954 |
+
self.mode = mode
|
955 |
+
|
956 |
+
def forward(self, x):
|
957 |
+
return F.interpolate(x, size=self.size, scale_factor=self.scale_factor, mode=self.mode)
|
958 |
+
|
959 |
+
|
960 |
+
class HiResNeck(nn.Module):
|
961 |
+
"""
|
962 |
+
The block is used to output dense features from all stages
|
963 |
+
Otherwise, by default, only the last stage features are returned with FasterViTv2
|
964 |
+
"""
|
965 |
+
def __init__(self, dim, depths, neck_start_stage, full_features_head_dim, downsample_enabled):
|
966 |
+
|
967 |
+
'''
|
968 |
+
Hi Resolution neck to support output of high res features that are useful for dense tasks.
|
969 |
+
depths - total number of layers in the base model
|
970 |
+
neck_start_stage - when to start the neck, 0 - start from the first stage, 1 - start from the second stage etc.
|
971 |
+
earlier layers result in higher resolution features at the cost of compute
|
972 |
+
full_features_head_dim - number of channels in the dense features head
|
973 |
+
'''
|
974 |
+
super().__init__()
|
975 |
+
# create feature projection layers for segmentation output
|
976 |
+
self.neck_features_proj = nn.ModuleList()
|
977 |
+
self.neck_start_stage = neck_start_stage
|
978 |
+
upsample_ratio = 1
|
979 |
+
for i in range(len(depths)):
|
980 |
+
level_n_features_output = int(dim * 2 ** i)
|
981 |
+
|
982 |
+
if self.neck_start_stage > i: continue
|
983 |
+
|
984 |
+
if (upsample_ratio > 1) or full_features_head_dim!=level_n_features_output:
|
985 |
+
feature_projection = nn.Sequential()
|
986 |
+
if False:
|
987 |
+
feature_projection.add_module("norm",nn.BatchNorm2d(level_n_features_output)) #fast, but worse
|
988 |
+
feature_projection.add_module("dconv", nn.ConvTranspose2d(level_n_features_output,
|
989 |
+
full_features_head_dim, kernel_size=upsample_ratio, stride=upsample_ratio))
|
990 |
+
else:
|
991 |
+
# B, in_channels, H, W -> B, in_channels, H*upsample_ratio, W*upsample_ratio
|
992 |
+
# print("upsample ratio", upsample_ratio, level_n_features_output, level_n_features_output)
|
993 |
+
feature_projection.add_module("upsample", InterpolateLayer(scale_factor=upsample_ratio, mode='nearest'))
|
994 |
+
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))
|
995 |
+
feature_projection.add_module("norm",nn.BatchNorm2d(level_n_features_output))
|
996 |
+
# B, in_channels, H*upsample_ratio, W*upsample_ratio -> B, full_features_head_dim, H*upsample_ratio, W*upsample_ratio
|
997 |
+
feature_projection.add_module("conv2", nn.Conv2d(level_n_features_output, full_features_head_dim, kernel_size=1, stride=1, padding=0))
|
998 |
+
else:
|
999 |
+
feature_projection = nn.Sequential()
|
1000 |
+
|
1001 |
+
self.neck_features_proj.append(feature_projection)
|
1002 |
+
|
1003 |
+
if i>0 and downsample_enabled[i]:
|
1004 |
+
upsample_ratio *= 2
|
1005 |
+
|
1006 |
+
def forward(self, x, il_level=-1, full_features=None):
|
1007 |
+
if self.neck_start_stage > il_level:
|
1008 |
+
return full_features
|
1009 |
+
|
1010 |
+
if full_features is None:
|
1011 |
+
full_features = self.neck_features_proj[il_level - self.neck_start_stage](x)
|
1012 |
+
else:
|
1013 |
+
#upsample torch tensor x to match full_features size, and add to full_features
|
1014 |
+
feature_projection = self.neck_features_proj[il_level - self.neck_start_stage](x)
|
1015 |
+
if feature_projection.shape[2] != full_features.shape[2] or feature_projection.shape[3] != full_features.shape[3]:
|
1016 |
+
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]))
|
1017 |
+
full_features = full_features + feature_projection
|
1018 |
+
return full_features
|
1019 |
+
|
1020 |
+
class FasterViT(nn.Module):
|
1021 |
+
"""
|
1022 |
+
FasterViT
|
1023 |
+
"""
|
1024 |
+
|
1025 |
+
def __init__(self,
|
1026 |
+
dim,
|
1027 |
+
in_dim,
|
1028 |
+
depths,
|
1029 |
+
window_size,
|
1030 |
+
mlp_ratio,
|
1031 |
+
num_heads,
|
1032 |
+
drop_path_rate=0.2,
|
1033 |
+
in_chans=3,
|
1034 |
+
num_classes=1000,
|
1035 |
+
qkv_bias=False,
|
1036 |
+
qk_scale=None,
|
1037 |
+
layer_scale=None,
|
1038 |
+
layer_scale_conv=None,
|
1039 |
+
layer_norm_last=False,
|
1040 |
+
sr_ratio = [1, 1, 1, 1],
|
1041 |
+
max_depth = -1,
|
1042 |
+
conv_base=False,
|
1043 |
+
use_swiglu=False,
|
1044 |
+
multi_query=False,
|
1045 |
+
norm_layer=nn.LayerNorm,
|
1046 |
+
drop_uniform=False,
|
1047 |
+
yolo_arch=False,
|
1048 |
+
shuffle_down=False,
|
1049 |
+
downsample_shuffle=False,
|
1050 |
+
return_full_features=False,
|
1051 |
+
full_features_head_dim=128,
|
1052 |
+
neck_start_stage=1,
|
1053 |
+
use_neck=False,
|
1054 |
+
use_shift=False,
|
1055 |
+
cpb_mlp_hidden=512,
|
1056 |
+
conv_groups_ratio=0,
|
1057 |
+
verbose: bool = False,
|
1058 |
+
**kwargs):
|
1059 |
+
"""
|
1060 |
+
Args:
|
1061 |
+
dim: feature size dimension.
|
1062 |
+
depths: number of layers in each stage.
|
1063 |
+
window_size: window size in each stage.
|
1064 |
+
mlp_ratio: MLP ratio.
|
1065 |
+
num_heads: number of heads in each stage.
|
1066 |
+
drop_path_rate: drop path rate.
|
1067 |
+
in_chans: number of input channels.
|
1068 |
+
num_classes: number of classes.
|
1069 |
+
qkv_bias: bool argument for query, key, value learnable bias.
|
1070 |
+
qk_scale: bool argument to scaling query, key.
|
1071 |
+
drop_rate: dropout rate.
|
1072 |
+
attn_drop_rate: attention dropout rate.
|
1073 |
+
norm_layer: normalization layer.
|
1074 |
+
layer_scale: layer scaling coefficient.
|
1075 |
+
return_full_features: output dense features as well as logits
|
1076 |
+
full_features_head_dim: number of channels in the dense features head
|
1077 |
+
neck_start_stage: a stage id to start full feature neck. Model has 4 stages, indix starts with 0
|
1078 |
+
for 224 resolution, the output of the stage before downsample:
|
1079 |
+
stage 0: 56x56, stage 1: 28x28, stage 2: 14x14, stage 3: 7x7
|
1080 |
+
use_neck: even for summarization embedding use neck
|
1081 |
+
use_shift: SWIN like window shifting but without masking attention
|
1082 |
+
conv_groups_ratio: will be used for conv blocks where there is no multires attention,
|
1083 |
+
if 0 then normal conv,
|
1084 |
+
if 1 then channels are independent,
|
1085 |
+
if -1 then no conv at all
|
1086 |
+
|
1087 |
+
"""
|
1088 |
+
super().__init__()
|
1089 |
+
|
1090 |
+
num_features = int(dim * 2 ** (len(depths) - 1))
|
1091 |
+
self.num_classes = num_classes
|
1092 |
+
self.patch_embed = PatchEmbed(in_chans=in_chans, in_dim=in_dim, dim=dim, shuffle_down=shuffle_down)
|
1093 |
+
# set return_full_features true if we want to return full features from all stages
|
1094 |
+
self.return_full_features = return_full_features
|
1095 |
+
self.use_neck = use_neck
|
1096 |
+
|
1097 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
|
1098 |
+
if drop_uniform:
|
1099 |
+
dpr = [drop_path_rate for x in range(sum(depths))]
|
1100 |
+
|
1101 |
+
if not isinstance(max_depth, list): max_depth = [max_depth] * len(depths)
|
1102 |
+
|
1103 |
+
self.levels = nn.ModuleList()
|
1104 |
+
for i in range(len(depths)):
|
1105 |
+
conv = True if (i == 0 or i == 1) else False
|
1106 |
+
|
1107 |
+
level = FasterViTLayer(dim=int(dim * 2 ** i),
|
1108 |
+
depth=depths[i],
|
1109 |
+
num_heads=num_heads[i],
|
1110 |
+
window_size=window_size[i],
|
1111 |
+
mlp_ratio=mlp_ratio,
|
1112 |
+
qkv_bias=qkv_bias,
|
1113 |
+
qk_scale=qk_scale,
|
1114 |
+
conv=conv,
|
1115 |
+
drop_path=dpr[sum(depths[:i]):sum(depths[:i + 1])],
|
1116 |
+
downsample=(i < len(depths) - 1),
|
1117 |
+
layer_scale=layer_scale,
|
1118 |
+
layer_scale_conv=layer_scale_conv,
|
1119 |
+
sr_ratio=sr_ratio[i],
|
1120 |
+
use_swiglu=use_swiglu,
|
1121 |
+
multi_query=multi_query,
|
1122 |
+
norm_layer=norm_layer,
|
1123 |
+
yolo_arch=yolo_arch,
|
1124 |
+
downsample_shuffle=downsample_shuffle,
|
1125 |
+
conv_base=conv_base,
|
1126 |
+
cpb_mlp_hidden=cpb_mlp_hidden,
|
1127 |
+
use_shift=use_shift,
|
1128 |
+
conv_groups_ratio=conv_groups_ratio,
|
1129 |
+
verbose=verbose)
|
1130 |
+
|
1131 |
+
self.levels.append(level)
|
1132 |
+
|
1133 |
+
if self.return_full_features or self.use_neck:
|
1134 |
+
#num_heads
|
1135 |
+
downsample_enabled = [self.levels[i-1].downsample is not None for i in range(len(self.levels))]
|
1136 |
+
self.high_res_neck = HiResNeck(dim, depths, neck_start_stage, full_features_head_dim, downsample_enabled)
|
1137 |
+
|
1138 |
+
self.switched_to_deploy = False
|
1139 |
+
|
1140 |
+
self.norm = LayerNorm2d(num_features) if layer_norm_last else nn.BatchNorm2d(num_features)
|
1141 |
+
self.avgpool = nn.AdaptiveAvgPool2d(1)
|
1142 |
+
self.head = nn.Linear(num_features, num_classes) if num_classes > 0 else nn.Identity()
|
1143 |
+
self.apply(self._init_weights)
|
1144 |
+
|
1145 |
+
def _init_weights(self, m):
|
1146 |
+
if isinstance(m, nn.Linear):
|
1147 |
+
trunc_normal_(m.weight, std=.02)
|
1148 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
1149 |
+
nn.init.constant_(m.bias, 0)
|
1150 |
+
elif isinstance(m, nn.LayerNorm):
|
1151 |
+
nn.init.constant_(m.bias, 0)
|
1152 |
+
nn.init.constant_(m.weight, 1.0)
|
1153 |
+
elif isinstance(m, LayerNorm2d):
|
1154 |
+
nn.init.constant_(m.bias, 0)
|
1155 |
+
nn.init.constant_(m.weight, 1.0)
|
1156 |
+
elif isinstance(m, nn.BatchNorm2d):
|
1157 |
+
nn.init.ones_(m.weight)
|
1158 |
+
nn.init.zeros_(m.bias)
|
1159 |
+
|
1160 |
+
@torch.jit.ignore
|
1161 |
+
def no_weight_decay_keywords(self):
|
1162 |
+
return {'rpb'}
|
1163 |
+
|
1164 |
+
def forward_features(self, x):
|
1165 |
+
x = self.patch_embed(x)
|
1166 |
+
full_features = None
|
1167 |
+
for il, level in enumerate(self.levels):
|
1168 |
+
x, pre_downsample_x = level(x)
|
1169 |
+
|
1170 |
+
if self.return_full_features or self.use_neck:
|
1171 |
+
full_features = self.high_res_neck(pre_downsample_x, il, full_features)
|
1172 |
+
|
1173 |
+
# x = self.norm(full_features if (self.return_full_features or self.use_neck) else x)
|
1174 |
+
x = self.norm(x) # new version for
|
1175 |
+
|
1176 |
+
if not self.return_full_features:
|
1177 |
+
return x, None
|
1178 |
+
|
1179 |
+
return x, full_features
|
1180 |
+
|
1181 |
+
def forward(self, x):
|
1182 |
+
x, full_features = self.forward_features(x)
|
1183 |
+
|
1184 |
+
x = self.avgpool(x)
|
1185 |
+
x = torch.flatten(x, 1)
|
1186 |
+
|
1187 |
+
x = self.head(x)
|
1188 |
+
if full_features is not None:
|
1189 |
+
return x, full_features
|
1190 |
+
return x
|
1191 |
+
|
1192 |
+
def switch_to_deploy(self):
|
1193 |
+
'''
|
1194 |
+
A method to perform model self-compression
|
1195 |
+
merges BN into conv layers
|
1196 |
+
converts MLP relative positional bias into precomputed buffers
|
1197 |
+
'''
|
1198 |
+
if not self.switched_to_deploy:
|
1199 |
+
for level in [self.patch_embed, self.levels, self.head]:
|
1200 |
+
for module in level.modules():
|
1201 |
+
if hasattr(module, 'switch_to_deploy'):
|
1202 |
+
module.switch_to_deploy()
|
1203 |
+
self.switched_to_deploy = True
|
1204 |
+
|
1205 |
+
|
1206 |
+
def change_window_size(self, new_window_size):
|
1207 |
+
"""
|
1208 |
+
FasterViT employs windowed attention, which may be sensitive to the choice of this parameter,
|
1209 |
+
especially in cases of uneven partitioning of the feature maps.
|
1210 |
+
FasterViT allows for the adjustment of the window size after training,
|
1211 |
+
making it adaptable to different input image resolutions.
|
1212 |
+
The recommended values for window size based on input resolution are as follows:
|
1213 |
+
|
1214 |
+
Input Resolution | Window Size
|
1215 |
+
224 | 7
|
1216 |
+
256 | 8
|
1217 |
+
386 | 12
|
1218 |
+
512 | 16
|
1219 |
+
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
|
1220 |
+
img_res/16/2
|
1221 |
+
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.
|
1222 |
+
Manual way to change resolution -> model.change_window_size(resolution)
|
1223 |
+
"""
|
1224 |
+
window_size = new_window_size
|
1225 |
+
print(f"Setting window size to {window_size}")
|
1226 |
+
for module in self.modules():
|
1227 |
+
if hasattr(module, "window_size"):
|
1228 |
+
# check if tuple or a number
|
1229 |
+
if isinstance(module.window_size, tuple):
|
1230 |
+
if module.window_size[0] != window_size:
|
1231 |
+
module.window_size = (window_size, window_size)
|
1232 |
+
elif isinstance(module.window_size, list):
|
1233 |
+
if module.window_size[0] != window_size:
|
1234 |
+
module.window_size = [window_size, window_size]
|
1235 |
+
else:
|
1236 |
+
module.window_size = window_size
|
1237 |
+
|
1238 |
+
|
1239 |
+
def set_optimal_window_size(self, image_dim, max_window_size = 16):
|
1240 |
+
"""
|
1241 |
+
Using hand picked window size for various resolutions.
|
1242 |
+
|
1243 |
+
FasterViT employs windowed attention, which may be sensitive to the choice of this parameter,
|
1244 |
+
especially in cases of uneven partitioning of the feature maps.
|
1245 |
+
FasterViT allows for the adjustment of the window size after training,
|
1246 |
+
making it adaptable to different input image resolutions.
|
1247 |
+
The recommended values for window size based on input resolution are as follows:
|
1248 |
+
|
1249 |
+
Input Resolution | Window Size
|
1250 |
+
224 | 7
|
1251 |
+
256 | 8
|
1252 |
+
386 | 12
|
1253 |
+
512 | 16
|
1254 |
+
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
|
1255 |
+
img_res/16/2
|
1256 |
+
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.
|
1257 |
+
Manual way to change resolution -> model.change_window_size(resolution)
|
1258 |
+
|
1259 |
+
"""
|
1260 |
+
# import math
|
1261 |
+
|
1262 |
+
def divisorGenerator(n):
|
1263 |
+
large_divisors = []
|
1264 |
+
for i in range(1, int(math.sqrt(n) + 1)):
|
1265 |
+
if n % i == 0:
|
1266 |
+
yield i
|
1267 |
+
if i*i != n:
|
1268 |
+
large_divisors.append(n / i)
|
1269 |
+
for divisor in reversed(large_divisors):
|
1270 |
+
yield divisor
|
1271 |
+
|
1272 |
+
if isinstance(image_dim, list) or isinstance(image_dim, tuple):
|
1273 |
+
image_dim = min(image_dim)
|
1274 |
+
|
1275 |
+
# we do windowed attention in the 3rd stage for the first time, therefore //16,
|
1276 |
+
# we do subsampled attention with downsample by 2 so need to get //32 actually
|
1277 |
+
# ideally we should rewrite this to be dependent on the structure of the model like what if subsampled is removed etc
|
1278 |
+
all_divisors = np.array(list(divisorGenerator(image_dim//32)))
|
1279 |
+
new_window_size = int(min(all_divisors[all_divisors <= max_window_size][-1], max_window_size))
|
1280 |
+
|
1281 |
+
# for image_dim in [128, 224, 256, 384, 512, 768, 1024]:
|
1282 |
+
# all_divisors = np.array(list(divisorGenerator(image_dim//32)))
|
1283 |
+
# new_window_size = int(min(all_divisors[all_divisors <= max_window_size][-1], max_window_size))
|
1284 |
+
# print(f"Setting window size to {new_window_size} for image resolution {image_dim}")
|
1285 |
+
|
1286 |
+
self.change_window_size(new_window_size = new_window_size)
|
1287 |
+
|
1288 |
+
# 83.44200001953125
|
1289 |
+
@register_model
|
1290 |
+
def fastervit2_small(pretrained=False, **kwargs): #,
|
1291 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1292 |
+
num_heads=[2, 4, 8, 16],
|
1293 |
+
window_size=[8, 8, [7, 7], 7],
|
1294 |
+
dim=96,
|
1295 |
+
in_dim=64,
|
1296 |
+
mlp_ratio=4,
|
1297 |
+
drop_path_rate=0.2,
|
1298 |
+
sr_ratio=[1, 1, [1, 2], 1],
|
1299 |
+
use_swiglu=False,
|
1300 |
+
downsample_shuffle=False,
|
1301 |
+
yolo_arch=True,
|
1302 |
+
shuffle_down=False,
|
1303 |
+
**kwargs)
|
1304 |
+
if pretrained:
|
1305 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1306 |
+
return model
|
1307 |
+
|
1308 |
+
# 82.61
|
1309 |
+
@register_model
|
1310 |
+
def fastervit2_tiny(pretrained=False, **kwargs): #,
|
1311 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1312 |
+
num_heads=[2, 4, 8, 16],
|
1313 |
+
window_size=[8, 8, [7, 7], 7],
|
1314 |
+
dim=80,
|
1315 |
+
in_dim=64,
|
1316 |
+
mlp_ratio=4,
|
1317 |
+
drop_path_rate=0.2,
|
1318 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1319 |
+
use_swiglu=False,
|
1320 |
+
downsample_shuffle=False,
|
1321 |
+
yolo_arch=True,
|
1322 |
+
shuffle_down=False,
|
1323 |
+
**kwargs)
|
1324 |
+
if pretrained:
|
1325 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1326 |
+
return model
|
1327 |
+
|
1328 |
+
#'top1', 84.31800001220704
|
1329 |
+
@register_model
|
1330 |
+
def fastervit2_base(pretrained=False, **kwargs):
|
1331 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1332 |
+
num_heads=[2, 4, 8, 16],
|
1333 |
+
window_size=[8, 8, [7, 7], 7],
|
1334 |
+
dim=128,
|
1335 |
+
in_dim=64,
|
1336 |
+
mlp_ratio=4,
|
1337 |
+
drop_path_rate=0.2,
|
1338 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1339 |
+
use_swiglu=False,
|
1340 |
+
yolo_arch=True,
|
1341 |
+
shuffle_down=False,
|
1342 |
+
conv_base=True,
|
1343 |
+
**kwargs)
|
1344 |
+
if pretrained:
|
1345 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1346 |
+
return model
|
1347 |
+
|
1348 |
+
#84.39999999267579
|
1349 |
+
@register_model
|
1350 |
+
def fastervit2_base_v1(pretrained=False, **kwargs):
|
1351 |
+
model = FasterViT(depths=[4, 4, 5, 5],
|
1352 |
+
num_heads=[2, 4, 8, 16],
|
1353 |
+
window_size=[8, 8, [7, 7], 7],
|
1354 |
+
dim=128,
|
1355 |
+
in_dim=64,
|
1356 |
+
mlp_ratio=4,
|
1357 |
+
drop_path_rate=0.2,
|
1358 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1359 |
+
use_swiglu=False,
|
1360 |
+
yolo_arch=True,
|
1361 |
+
shuffle_down=False,
|
1362 |
+
conv_base=True,
|
1363 |
+
downsample_shuffle=False,
|
1364 |
+
**kwargs)
|
1365 |
+
if pretrained:
|
1366 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1367 |
+
return model
|
1368 |
+
|
1369 |
+
@register_model
|
1370 |
+
def fastervit2_base_fullres1(pretrained=False, **kwargs):
|
1371 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1372 |
+
num_heads=[2, 4, 8, 16],
|
1373 |
+
window_size=[8, 8, [7, 7], 7],
|
1374 |
+
dim=128,
|
1375 |
+
in_dim=64,
|
1376 |
+
mlp_ratio=4,
|
1377 |
+
drop_path_rate=0.2,
|
1378 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1379 |
+
use_swiglu=False,
|
1380 |
+
yolo_arch=True,
|
1381 |
+
shuffle_down=False,
|
1382 |
+
conv_base=True,
|
1383 |
+
use_neck=True,
|
1384 |
+
full_features_head_dim=1024,
|
1385 |
+
neck_start_stage=2,
|
1386 |
+
**kwargs)
|
1387 |
+
if pretrained:
|
1388 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1389 |
+
return model
|
1390 |
+
|
1391 |
+
@register_model
|
1392 |
+
def fastervit2_base_fullres2(pretrained=False, **kwargs):
|
1393 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1394 |
+
num_heads=[2, 4, 8, 16],
|
1395 |
+
window_size=[8, 8, [7, 7], 7],
|
1396 |
+
dim=128,
|
1397 |
+
in_dim=64,
|
1398 |
+
mlp_ratio=4,
|
1399 |
+
drop_path_rate=0.2,
|
1400 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1401 |
+
use_swiglu=False,
|
1402 |
+
yolo_arch=True,
|
1403 |
+
shuffle_down=False,
|
1404 |
+
conv_base=True,
|
1405 |
+
use_neck=True,
|
1406 |
+
full_features_head_dim=512,
|
1407 |
+
neck_start_stage=1,
|
1408 |
+
**kwargs)
|
1409 |
+
if pretrained:
|
1410 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1411 |
+
return model
|
1412 |
+
|
1413 |
+
@register_model
|
1414 |
+
def fastervit2_base_fullres3(pretrained=False, **kwargs):
|
1415 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1416 |
+
num_heads=[2, 4, 8, 16],
|
1417 |
+
window_size=[8, 8, [7, 7], 7],
|
1418 |
+
dim=128,
|
1419 |
+
in_dim=64,
|
1420 |
+
mlp_ratio=4,
|
1421 |
+
drop_path_rate=0.2,
|
1422 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1423 |
+
use_swiglu=False,
|
1424 |
+
yolo_arch=True,
|
1425 |
+
shuffle_down=False,
|
1426 |
+
conv_base=True,
|
1427 |
+
use_neck=True,
|
1428 |
+
full_features_head_dim=256,
|
1429 |
+
neck_start_stage=1,
|
1430 |
+
**kwargs)
|
1431 |
+
if pretrained:
|
1432 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1433 |
+
return model
|
1434 |
+
|
1435 |
+
@register_model
|
1436 |
+
def fastervit2_base_fullres4(pretrained=False, **kwargs):
|
1437 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1438 |
+
num_heads=[2, 4, 8, 16],
|
1439 |
+
window_size=[8, 8, [7, 7], 7],
|
1440 |
+
dim=128,
|
1441 |
+
in_dim=64,
|
1442 |
+
mlp_ratio=4,
|
1443 |
+
drop_path_rate=0.2,
|
1444 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1445 |
+
use_swiglu=False,
|
1446 |
+
yolo_arch=True,
|
1447 |
+
shuffle_down=False,
|
1448 |
+
conv_base=True,
|
1449 |
+
use_neck=True,
|
1450 |
+
full_features_head_dim=256,
|
1451 |
+
neck_start_stage=2,
|
1452 |
+
**kwargs)
|
1453 |
+
if pretrained:
|
1454 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1455 |
+
return model
|
1456 |
+
|
1457 |
+
@register_model
|
1458 |
+
def fastervit2_base_fullres5(pretrained=False, **kwargs):
|
1459 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1460 |
+
num_heads=[2, 4, 8, 16],
|
1461 |
+
window_size=[8, 8, [7, 7], 7],
|
1462 |
+
dim=128,
|
1463 |
+
in_dim=64,
|
1464 |
+
mlp_ratio=4,
|
1465 |
+
drop_path_rate=0.2,
|
1466 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1467 |
+
use_swiglu=False,
|
1468 |
+
yolo_arch=True,
|
1469 |
+
shuffle_down=False,
|
1470 |
+
conv_base=True,
|
1471 |
+
use_neck=True,
|
1472 |
+
full_features_head_dim=512,
|
1473 |
+
neck_start_stage=2,
|
1474 |
+
**kwargs)
|
1475 |
+
if pretrained:
|
1476 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1477 |
+
return model
|
1478 |
+
|
1479 |
+
#84.87
|
1480 |
+
@register_model
|
1481 |
+
def fastervit2_large(pretrained=False, **kwargs):
|
1482 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1483 |
+
num_heads=[2, 4, 8, 16],
|
1484 |
+
window_size=[8, 8, [7, 7], 7],
|
1485 |
+
dim=128+64,
|
1486 |
+
in_dim=64,
|
1487 |
+
mlp_ratio=4,
|
1488 |
+
drop_path_rate=0.3,
|
1489 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1490 |
+
use_swiglu=False,
|
1491 |
+
yolo_arch=False,
|
1492 |
+
shuffle_down=False,
|
1493 |
+
cpb_mlp_hidden=64,
|
1494 |
+
conv_base=True,
|
1495 |
+
**kwargs)
|
1496 |
+
if pretrained:
|
1497 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1498 |
+
return model
|
1499 |
+
|
1500 |
+
@register_model
|
1501 |
+
def fastervit2_large_fullres(pretrained=False, **kwargs):
|
1502 |
+
model = FasterViT(
|
1503 |
+
depths=[3, 3, 5, 5],
|
1504 |
+
num_heads=[2, 4, 8, 16],
|
1505 |
+
window_size=[None, None, [7, 7], 7],
|
1506 |
+
dim=192,
|
1507 |
+
in_dim=64,
|
1508 |
+
mlp_ratio=4,
|
1509 |
+
drop_path_rate=0.0,
|
1510 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1511 |
+
use_swiglu=False,
|
1512 |
+
yolo_arch=True,
|
1513 |
+
shuffle_down=False,
|
1514 |
+
conv_base=True,
|
1515 |
+
use_neck=True,
|
1516 |
+
full_features_head_dim=1536,
|
1517 |
+
neck_start_stage=2,
|
1518 |
+
**kwargs,
|
1519 |
+
)
|
1520 |
+
if pretrained:
|
1521 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1522 |
+
return model
|
1523 |
+
|
1524 |
+
|
1525 |
+
@register_model
|
1526 |
+
def fastervit2_large_fullres_ws8(pretrained=False, **kwargs):
|
1527 |
+
model = FasterViT(
|
1528 |
+
depths=[3, 3, 5, 5],
|
1529 |
+
num_heads=[2, 4, 8, 16],
|
1530 |
+
window_size=[None, None, [8, 8], 8],
|
1531 |
+
dim=192,
|
1532 |
+
in_dim=64,
|
1533 |
+
mlp_ratio=4,
|
1534 |
+
drop_path_rate=0.0,
|
1535 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1536 |
+
use_swiglu=False,
|
1537 |
+
yolo_arch=True,
|
1538 |
+
shuffle_down=False,
|
1539 |
+
conv_base=True,
|
1540 |
+
use_neck=True,
|
1541 |
+
full_features_head_dim=1536,
|
1542 |
+
neck_start_stage=2,
|
1543 |
+
**kwargs,
|
1544 |
+
)
|
1545 |
+
if pretrained:
|
1546 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1547 |
+
return model
|
1548 |
+
|
1549 |
+
|
1550 |
+
@register_model
|
1551 |
+
def fastervit2_large_fullres_ws16(pretrained=False, **kwargs):
|
1552 |
+
model = FasterViT(
|
1553 |
+
depths=[3, 3, 5, 5],
|
1554 |
+
num_heads=[2, 4, 8, 16],
|
1555 |
+
window_size=[None, None, [16, 16], 16],
|
1556 |
+
dim=192,
|
1557 |
+
in_dim=64,
|
1558 |
+
mlp_ratio=4,
|
1559 |
+
drop_path_rate=0.0,
|
1560 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1561 |
+
use_swiglu=False,
|
1562 |
+
yolo_arch=True,
|
1563 |
+
shuffle_down=False,
|
1564 |
+
conv_base=True,
|
1565 |
+
use_neck=True,
|
1566 |
+
full_features_head_dim=1536,
|
1567 |
+
neck_start_stage=2,
|
1568 |
+
**kwargs,
|
1569 |
+
)
|
1570 |
+
if pretrained:
|
1571 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1572 |
+
return model
|
1573 |
+
|
1574 |
+
|
1575 |
+
@register_model
|
1576 |
+
def fastervit2_large_fullres_ws32(pretrained=False, **kwargs):
|
1577 |
+
model = FasterViT(
|
1578 |
+
depths=[3, 3, 5, 5],
|
1579 |
+
num_heads=[2, 4, 8, 16],
|
1580 |
+
window_size=[None, None, [32, 32], 32],
|
1581 |
+
dim=192,
|
1582 |
+
in_dim=64,
|
1583 |
+
mlp_ratio=4,
|
1584 |
+
drop_path_rate=0.0,
|
1585 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1586 |
+
use_swiglu=False,
|
1587 |
+
yolo_arch=True,
|
1588 |
+
shuffle_down=False,
|
1589 |
+
conv_base=True,
|
1590 |
+
use_neck=True,
|
1591 |
+
full_features_head_dim=1536,
|
1592 |
+
neck_start_stage=2,
|
1593 |
+
**kwargs,
|
1594 |
+
)
|
1595 |
+
if pretrained:
|
1596 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1597 |
+
return model
|
1598 |
+
|
1599 |
+
#85.23% top1
|
1600 |
+
@register_model
|
1601 |
+
def fastervit2_xlarge(pretrained=False, **kwargs):
|
1602 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1603 |
+
num_heads=[2, 4, 8, 16],
|
1604 |
+
window_size=[8, 8, [7, 7], 7],
|
1605 |
+
dim=128+128+64,
|
1606 |
+
in_dim=64,
|
1607 |
+
mlp_ratio=4,
|
1608 |
+
drop_path_rate=0.4,
|
1609 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1610 |
+
use_swiglu=False,
|
1611 |
+
yolo_arch=False,
|
1612 |
+
shuffle_down=False,
|
1613 |
+
cpb_mlp_hidden=64,
|
1614 |
+
**kwargs)
|
1615 |
+
if pretrained:
|
1616 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1617 |
+
return model
|
1618 |
+
|
1619 |
+
@register_model
|
1620 |
+
def fastervit2_huge(pretrained=False, **kwargs):
|
1621 |
+
model = FasterViT(depths=[3, 3, 5, 5],
|
1622 |
+
num_heads=[2, 4, 8, 16],
|
1623 |
+
window_size=[8, 8, [7, 7], 7],
|
1624 |
+
dim=128+128+128+64,
|
1625 |
+
in_dim=64,
|
1626 |
+
mlp_ratio=4,
|
1627 |
+
drop_path_rate=0.2,
|
1628 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1629 |
+
use_swiglu=False,
|
1630 |
+
yolo_arch=True,
|
1631 |
+
shuffle_down=False,
|
1632 |
+
**kwargs)
|
1633 |
+
if pretrained:
|
1634 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1635 |
+
return model
|
1636 |
+
|
1637 |
+
|
1638 |
+
# 81.61
|
1639 |
+
@register_model
|
1640 |
+
def fastervit2_xtiny(pretrained=False, **kwargs): #,
|
1641 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1642 |
+
num_heads=[2, 4, 8, 16],
|
1643 |
+
window_size=[8, 8, [7, 7], 7],
|
1644 |
+
dim=64,
|
1645 |
+
in_dim=64,
|
1646 |
+
mlp_ratio=4,
|
1647 |
+
drop_path_rate=0.1,
|
1648 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1649 |
+
use_swiglu=False,
|
1650 |
+
downsample_shuffle=False,
|
1651 |
+
yolo_arch=True,
|
1652 |
+
shuffle_down=False,
|
1653 |
+
cpb_mlp_hidden=64,
|
1654 |
+
**kwargs)
|
1655 |
+
if pretrained:
|
1656 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1657 |
+
return model
|
1658 |
+
|
1659 |
+
|
1660 |
+
# 80.19
|
1661 |
+
@register_model
|
1662 |
+
def fastervit2_xxtiny(pretrained=False, **kwargs): #,
|
1663 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1664 |
+
num_heads=[2, 4, 8, 16],
|
1665 |
+
window_size=[8, 8, [7, 7], 7],
|
1666 |
+
dim=48,
|
1667 |
+
in_dim=64,
|
1668 |
+
mlp_ratio=4,
|
1669 |
+
drop_path_rate=0.05,
|
1670 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1671 |
+
use_swiglu=False,
|
1672 |
+
downsample_shuffle=False,
|
1673 |
+
yolo_arch=True,
|
1674 |
+
shuffle_down=False,
|
1675 |
+
cpb_mlp_hidden=64,
|
1676 |
+
**kwargs)
|
1677 |
+
if pretrained:
|
1678 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1679 |
+
return model
|
1680 |
+
|
1681 |
+
@register_model
|
1682 |
+
# 77.0
|
1683 |
+
def fastervit2_xxxtiny(pretrained=False, **kwargs): #,
|
1684 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1685 |
+
num_heads=[2, 4, 8, 16],
|
1686 |
+
window_size=[8, 8, [7, 7], 7],
|
1687 |
+
dim=32,
|
1688 |
+
in_dim=32,
|
1689 |
+
mlp_ratio=4,
|
1690 |
+
drop_path_rate=0.0,
|
1691 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1692 |
+
use_swiglu=False,
|
1693 |
+
downsample_shuffle=False,
|
1694 |
+
yolo_arch=True,
|
1695 |
+
shuffle_down=False,
|
1696 |
+
cpb_mlp_hidden=64,
|
1697 |
+
**kwargs)
|
1698 |
+
if pretrained:
|
1699 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1700 |
+
return model
|
1701 |
+
|
1702 |
+
|
1703 |
+
@register_model
|
1704 |
+
def fastervit2_xxxtiny_fullres(pretrained=False, **kwargs):
|
1705 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1706 |
+
num_heads=[2, 4, 8, 16],
|
1707 |
+
window_size=[8, 8, [7, 7], 7],
|
1708 |
+
dim=32,
|
1709 |
+
in_dim=32,
|
1710 |
+
mlp_ratio=4,
|
1711 |
+
drop_path_rate=0.0,
|
1712 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1713 |
+
use_swiglu=False,
|
1714 |
+
downsample_shuffle=False,
|
1715 |
+
yolo_arch=True,
|
1716 |
+
shuffle_down=False,
|
1717 |
+
cpb_mlp_hidden=64,
|
1718 |
+
use_neck=True,
|
1719 |
+
full_features_head_dim=128,
|
1720 |
+
neck_start_stage=1,
|
1721 |
+
conv_groups_ratio = 1,
|
1722 |
+
**kwargs)
|
1723 |
+
if pretrained:
|
1724 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1725 |
+
return model
|
1726 |
+
|
1727 |
+
@register_model
|
1728 |
+
def eradio_xxxtiny(pretrained=False, **kwargs): # ,
|
1729 |
+
model = FasterViT(
|
1730 |
+
depths=[1, 3, 4, 5],
|
1731 |
+
num_heads=[2, 4, 8, 16],
|
1732 |
+
window_size=[None, None, [16, 16], 16],
|
1733 |
+
dim=32,
|
1734 |
+
in_dim=32,
|
1735 |
+
mlp_ratio=4,
|
1736 |
+
drop_path_rate=0.0,
|
1737 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1738 |
+
use_swiglu=False,
|
1739 |
+
yolo_arch=True,
|
1740 |
+
shuffle_down=False,
|
1741 |
+
conv_base=True,
|
1742 |
+
use_neck=True,
|
1743 |
+
full_features_head_dim=256,
|
1744 |
+
neck_start_stage=2,
|
1745 |
+
**kwargs,
|
1746 |
+
)
|
1747 |
+
if pretrained:
|
1748 |
+
model.load_state_dict(torch.load(pretrained))
|
1749 |
+
return model
|
1750 |
+
|
1751 |
+
@register_model
|
1752 |
+
def eradio_xxxtiny_8x_ws12(pretrained=False, **kwargs):
|
1753 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1754 |
+
num_heads=[2, 4, 8, 16],
|
1755 |
+
window_size=[None, None, [12, 12], 12],
|
1756 |
+
dim=32,
|
1757 |
+
in_dim=32,
|
1758 |
+
mlp_ratio=4,
|
1759 |
+
drop_path_rate=0.0,
|
1760 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1761 |
+
use_swiglu=False,
|
1762 |
+
downsample_shuffle=False,
|
1763 |
+
yolo_arch=True,
|
1764 |
+
shuffle_down=False,
|
1765 |
+
cpb_mlp_hidden=64,
|
1766 |
+
use_neck=True,
|
1767 |
+
full_features_head_dim=256,
|
1768 |
+
neck_start_stage=2,
|
1769 |
+
conv_groups_ratio = 1,
|
1770 |
+
**kwargs)
|
1771 |
+
if pretrained:
|
1772 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1773 |
+
return model
|
1774 |
+
|
1775 |
+
|
1776 |
+
@register_model
|
1777 |
+
def eradio_xxxtiny_8x_ws16(pretrained=False, **kwargs):
|
1778 |
+
model = FasterViT(depths=[1, 3, 4, 5],
|
1779 |
+
num_heads=[2, 4, 8, 16],
|
1780 |
+
window_size=[None, None, [16, 16], 16],
|
1781 |
+
dim=32,
|
1782 |
+
in_dim=32,
|
1783 |
+
mlp_ratio=4,
|
1784 |
+
drop_path_rate=0.0,
|
1785 |
+
sr_ratio=[1, 1, [2, 1], 1],
|
1786 |
+
use_swiglu=False,
|
1787 |
+
downsample_shuffle=False,
|
1788 |
+
yolo_arch=True,
|
1789 |
+
shuffle_down=False,
|
1790 |
+
cpb_mlp_hidden=64,
|
1791 |
+
use_neck=True,
|
1792 |
+
full_features_head_dim=256,
|
1793 |
+
neck_start_stage=1,
|
1794 |
+
conv_groups_ratio = 1,
|
1795 |
+
**kwargs)
|
1796 |
+
if pretrained:
|
1797 |
+
model.load_state_dict(torch.load(pretrained)["state_dict"])
|
1798 |
+
return model
|
1799 |
+
|
1800 |
+
@register_model
|
1801 |
+
def eradio(pretrained=False, **kwargs):
|
1802 |
+
return fastervit2_large_fullres_ws16(pretrained=pretrained, **kwargs)
|
extra_timm_models.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
|
9 |
+
from torch import nn
|
10 |
+
|
11 |
+
from timm.models import register_model
|
12 |
+
from timm.models.vision_transformer import VisionTransformer, _create_vision_transformer, Mlp
|
13 |
+
|
14 |
+
|
15 |
+
@register_model
|
16 |
+
def vit_tiny_patch14_224(pretrained=False, **kwargs) -> VisionTransformer:
|
17 |
+
""" ViT-Tiny (Vit-Ti/16)
|
18 |
+
"""
|
19 |
+
model_args = dict(patch_size=14, embed_dim=192, depth=12, num_heads=3)
|
20 |
+
model = _create_vision_transformer('vit_tiny_patch14_224', pretrained=pretrained, **dict(model_args, **kwargs))
|
21 |
+
return model
|
22 |
+
|
23 |
+
|
24 |
+
@register_model
|
25 |
+
def vit_small_patch14_224(pretrained=False, **kwargs) -> VisionTransformer:
|
26 |
+
""" ViT-Small (ViT-S/16)
|
27 |
+
"""
|
28 |
+
model_args = dict(patch_size=14, embed_dim=384, depth=12, num_heads=6)
|
29 |
+
model = _create_vision_transformer('vit_small_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs))
|
30 |
+
return model
|
31 |
+
|
32 |
+
|
33 |
+
@register_model
|
34 |
+
def vit_base_patch14_224(pretrained=False, **kwargs) -> VisionTransformer:
|
35 |
+
""" ViT-Base (ViT-B/14) from original paper (https://arxiv.org/abs/2010.11929).
|
36 |
+
ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer.
|
37 |
+
"""
|
38 |
+
model_args = dict(patch_size=14, embed_dim=768, depth=12, num_heads=12)
|
39 |
+
model = _create_vision_transformer('vit_base_patch14_224', pretrained=pretrained, **dict(model_args, **kwargs))
|
40 |
+
return model
|
41 |
+
|
42 |
+
|
43 |
+
@register_model
|
44 |
+
def vit_huge_patch16_224(pretrained=False, **kwargs) -> VisionTransformer:
|
45 |
+
""" ViT-Huge model (ViT-H/16) from original paper (https://arxiv.org/abs/2010.11929).
|
46 |
+
"""
|
47 |
+
model_args = dict(patch_size=16, embed_dim=1280, depth=32, num_heads=16)
|
48 |
+
if pretrained:
|
49 |
+
# There is no pretrained version of ViT-H/16, but we can adapt a ViT-H/14 for this purpose
|
50 |
+
model = _create_vision_transformer('vit_huge_patch14_clip_336', pretrained=True, **dict(model_args, pre_norm=True, **kwargs))
|
51 |
+
else:
|
52 |
+
model = _create_vision_transformer('vit_huge_patch16_224', pretrained=False, **dict(model_args, **kwargs))
|
53 |
+
return model
|
54 |
+
|
55 |
+
|
56 |
+
@register_model
|
57 |
+
def vit_huge_patch16_224_mlpnorm(pretrained=False, **kwargs) -> VisionTransformer:
|
58 |
+
""" ViT-Huge model (ViT-H/16) from original paper (https://arxiv.org/abs/2010.11929).
|
59 |
+
"""
|
60 |
+
model = vit_huge_patch16_224(pretrained=pretrained, **kwargs)
|
61 |
+
|
62 |
+
for m in model.modules():
|
63 |
+
if isinstance(m, Mlp) and not isinstance(m.norm, nn.LayerNorm):
|
64 |
+
m.norm = nn.LayerNorm(m.fc1.out_features)
|
65 |
+
|
66 |
+
return model
|
hf_model.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
# you may not use this file except in compliance with the License.
|
@@ -12,33 +12,55 @@
|
|
12 |
# See the License for the specific language governing permissions and
|
13 |
# limitations under the License.
|
14 |
from collections import namedtuple
|
15 |
-
from typing import Optional
|
16 |
|
17 |
from timm.models import VisionTransformer
|
18 |
import torch
|
19 |
from transformers import PretrainedConfig, PreTrainedModel
|
20 |
|
21 |
|
22 |
-
from .
|
23 |
-
|
|
|
|
|
|
|
24 |
from .input_conditioner import get_default_conditioner, InputConditioner
|
25 |
|
26 |
|
|
|
|
|
|
|
|
|
27 |
class RADIOConfig(PretrainedConfig):
|
28 |
"""Pretrained Hugging Face configuration for RADIO models."""
|
29 |
|
30 |
def __init__(
|
31 |
self,
|
32 |
args: Optional[dict] = None,
|
33 |
-
version: Optional[str] =
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
36 |
**kwargs,
|
37 |
):
|
38 |
self.args = args
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
self.version = version
|
40 |
-
|
41 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
super().__init__(**kwargs)
|
43 |
|
44 |
|
@@ -57,19 +79,48 @@ class RADIOModel(PreTrainedModel):
|
|
57 |
RADIOArgs = namedtuple("RADIOArgs", config.args.keys())
|
58 |
args = RADIOArgs(**config.args)
|
59 |
self.config = config
|
|
|
60 |
model = create_model_from_args(args)
|
61 |
input_conditioner: InputConditioner = get_default_conditioner()
|
62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
self.radio_model = RADIOModelBase(
|
64 |
model,
|
65 |
input_conditioner,
|
66 |
-
|
67 |
-
config.
|
|
|
|
|
|
|
|
|
68 |
)
|
69 |
|
70 |
@property
|
71 |
def model(self) -> VisionTransformer:
|
72 |
return self.radio_model.model
|
73 |
|
|
|
|
|
|
|
|
|
74 |
def forward(self, x: torch.Tensor):
|
75 |
return self.radio_model.forward(x)
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
# you may not use this file except in compliance with the License.
|
|
|
12 |
# See the License for the specific language governing permissions and
|
13 |
# limitations under the License.
|
14 |
from collections import namedtuple
|
15 |
+
from typing import Optional, List, Union
|
16 |
|
17 |
from timm.models import VisionTransformer
|
18 |
import torch
|
19 |
from transformers import PretrainedConfig, PreTrainedModel
|
20 |
|
21 |
|
22 |
+
from .common import RESOURCE_MAP, DEFAULT_VERSION
|
23 |
+
# Force import of eradio_model in order to register it.
|
24 |
+
from .eradio_model import eradio
|
25 |
+
from .radio_model import create_model_from_args
|
26 |
+
from .radio_model import RADIOModel as RADIOModelBase, Resolution
|
27 |
from .input_conditioner import get_default_conditioner, InputConditioner
|
28 |
|
29 |
|
30 |
+
# Register extra models
|
31 |
+
from .extra_timm_models import *
|
32 |
+
|
33 |
+
|
34 |
class RADIOConfig(PretrainedConfig):
|
35 |
"""Pretrained Hugging Face configuration for RADIO models."""
|
36 |
|
37 |
def __init__(
|
38 |
self,
|
39 |
args: Optional[dict] = None,
|
40 |
+
version: Optional[str] = DEFAULT_VERSION,
|
41 |
+
patch_size: Optional[int] = None,
|
42 |
+
max_resolution: Optional[int] = None,
|
43 |
+
preferred_resolution: Optional[Resolution] = None,
|
44 |
+
adaptor_names: Union[str, List[str]] = None,
|
45 |
+
vitdet_window_size: Optional[int] = None,
|
46 |
**kwargs,
|
47 |
):
|
48 |
self.args = args
|
49 |
+
for field in ["dtype", "amp_dtype"]:
|
50 |
+
if self.args is not None and field in self.args:
|
51 |
+
# Convert to a string in order to make it serializable.
|
52 |
+
# For example for torch.float32 we will store "float32",
|
53 |
+
# for "bfloat16" we will store "bfloat16".
|
54 |
+
self.args[field] = str(args[field]).split(".")[-1]
|
55 |
self.version = version
|
56 |
+
resource = RESOURCE_MAP[version]
|
57 |
+
self.patch_size = patch_size or resource.patch_size
|
58 |
+
self.max_resolution = max_resolution or resource.max_resolution
|
59 |
+
self.preferred_resolution = (
|
60 |
+
preferred_resolution or resource.preferred_resolution
|
61 |
+
)
|
62 |
+
self.adaptor_names = adaptor_names
|
63 |
+
self.vitdet_window_size = vitdet_window_size
|
64 |
super().__init__(**kwargs)
|
65 |
|
66 |
|
|
|
79 |
RADIOArgs = namedtuple("RADIOArgs", config.args.keys())
|
80 |
args = RADIOArgs(**config.args)
|
81 |
self.config = config
|
82 |
+
|
83 |
model = create_model_from_args(args)
|
84 |
input_conditioner: InputConditioner = get_default_conditioner()
|
85 |
|
86 |
+
dtype = getattr(args, "dtype", torch.float32)
|
87 |
+
if isinstance(dtype, str):
|
88 |
+
# Convert the dtype's string representation back to a dtype.
|
89 |
+
dtype = getattr(torch, dtype)
|
90 |
+
model.to(dtype=dtype)
|
91 |
+
input_conditioner.dtype = dtype
|
92 |
+
|
93 |
+
summary_idxs = torch.tensor(
|
94 |
+
[i for i, t in enumerate(args.teachers) if t.get("use_summary", True)],
|
95 |
+
dtype=torch.int64,
|
96 |
+
)
|
97 |
+
|
98 |
+
adaptor_names = config.adaptor_names
|
99 |
+
if adaptor_names is not None:
|
100 |
+
raise NotImplementedError(
|
101 |
+
f"Adaptors are not yet supported in Hugging Face models. Adaptor names: {adaptor_names}"
|
102 |
+
)
|
103 |
+
|
104 |
+
adaptors = dict()
|
105 |
+
|
106 |
self.radio_model = RADIOModelBase(
|
107 |
model,
|
108 |
input_conditioner,
|
109 |
+
summary_idxs=summary_idxs,
|
110 |
+
patch_size=config.patch_size,
|
111 |
+
max_resolution=config.max_resolution,
|
112 |
+
window_size=config.vitdet_window_size,
|
113 |
+
preferred_resolution=config.preferred_resolution,
|
114 |
+
adaptors=adaptors,
|
115 |
)
|
116 |
|
117 |
@property
|
118 |
def model(self) -> VisionTransformer:
|
119 |
return self.radio_model.model
|
120 |
|
121 |
+
@property
|
122 |
+
def input_conditioner(self) -> InputConditioner:
|
123 |
+
return self.radio_model.input_conditioner
|
124 |
+
|
125 |
def forward(self, x: torch.Tensor):
|
126 |
return self.radio_model.forward(x)
|
input_conditioner.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
@@ -19,20 +19,20 @@ class InputConditioner(nn.Module):
|
|
19 |
input_scale: float,
|
20 |
norm_mean: norm_t,
|
21 |
norm_std: norm_t,
|
22 |
-
dtype: torch.dtype =
|
23 |
):
|
24 |
super().__init__()
|
25 |
|
26 |
self.dtype = dtype
|
27 |
|
28 |
-
# self.input_scale = input_scale
|
29 |
self.register_buffer("norm_mean", _to_tensor(norm_mean) / input_scale)
|
30 |
self.register_buffer("norm_std", _to_tensor(norm_std) / input_scale)
|
31 |
|
32 |
def forward(self, x: torch.Tensor):
|
33 |
-
# x = x * self.input_scale
|
34 |
y = (x - self.norm_mean) / self.norm_std
|
35 |
-
|
|
|
|
|
36 |
|
37 |
|
38 |
def get_default_conditioner():
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
|
|
19 |
input_scale: float,
|
20 |
norm_mean: norm_t,
|
21 |
norm_std: norm_t,
|
22 |
+
dtype: torch.dtype = None,
|
23 |
):
|
24 |
super().__init__()
|
25 |
|
26 |
self.dtype = dtype
|
27 |
|
|
|
28 |
self.register_buffer("norm_mean", _to_tensor(norm_mean) / input_scale)
|
29 |
self.register_buffer("norm_std", _to_tensor(norm_std) / input_scale)
|
30 |
|
31 |
def forward(self, x: torch.Tensor):
|
|
|
32 |
y = (x - self.norm_mean) / self.norm_std
|
33 |
+
if self.dtype is not None:
|
34 |
+
y = y.to(self.dtype)
|
35 |
+
return y
|
36 |
|
37 |
|
38 |
def get_default_conditioner():
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df75c4351ef558af885acbf0d21ad53fd273e3720b5ae3d1e7d4a23df1ca9ed1
|
3 |
+
size 1306581088
|
radio_model.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
from typing import Optional, Callable, Union, Tuple, Any, Dict, NamedTuple
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from torch import nn
|
12 |
+
|
13 |
+
from timm.models import create_model, VisionTransformer
|
14 |
+
|
15 |
+
from .enable_cpe_support import enable_cpe
|
16 |
+
from .input_conditioner import InputConditioner
|
17 |
+
# Register extra models
|
18 |
+
from . import extra_timm_models
|
19 |
+
from .adaptor_base import AdaptorBase, RadioOutput, AdaptorInput
|
20 |
+
from . import eradio_model
|
21 |
+
|
22 |
+
|
23 |
+
class Resolution(NamedTuple):
|
24 |
+
height: int
|
25 |
+
width: int
|
26 |
+
|
27 |
+
|
28 |
+
class RADIOModel(nn.Module):
|
29 |
+
def __init__(
|
30 |
+
self,
|
31 |
+
model: nn.Module,
|
32 |
+
input_conditioner: InputConditioner,
|
33 |
+
patch_size: int,
|
34 |
+
max_resolution: int,
|
35 |
+
preferred_resolution: Resolution,
|
36 |
+
summary_idxs: Optional[torch.Tensor] = None,
|
37 |
+
window_size: int = None,
|
38 |
+
adaptors: Dict[str, AdaptorBase] = None,
|
39 |
+
):
|
40 |
+
super().__init__()
|
41 |
+
|
42 |
+
self.model = model
|
43 |
+
self.input_conditioner = input_conditioner
|
44 |
+
if summary_idxs is not None:
|
45 |
+
self.register_buffer('summary_idxs', summary_idxs)
|
46 |
+
else:
|
47 |
+
self.summary_idxs = None
|
48 |
+
|
49 |
+
self._preferred_resolution = preferred_resolution
|
50 |
+
self._patch_size = patch_size
|
51 |
+
self._max_resolution = max_resolution
|
52 |
+
self._window_size = window_size
|
53 |
+
|
54 |
+
adaptors = adaptors or dict()
|
55 |
+
self.adaptors = nn.ModuleDict(adaptors)
|
56 |
+
|
57 |
+
@property
|
58 |
+
def num_summary_tokens(self) -> int:
|
59 |
+
patch_gen = getattr(self.model, "patch_generator", None)
|
60 |
+
if patch_gen is not None:
|
61 |
+
return patch_gen.num_skip
|
62 |
+
elif self.model.global_pool == 'avg':
|
63 |
+
return 0
|
64 |
+
return 1
|
65 |
+
|
66 |
+
@property
|
67 |
+
def patch_size(self) -> int:
|
68 |
+
return self._patch_size
|
69 |
+
|
70 |
+
@property
|
71 |
+
def max_resolution(self) -> int:
|
72 |
+
return self._max_resolution
|
73 |
+
|
74 |
+
@property
|
75 |
+
def preferred_resolution(self) -> Resolution:
|
76 |
+
return self._preferred_resolution
|
77 |
+
|
78 |
+
@property
|
79 |
+
def window_size(self) -> int:
|
80 |
+
return self._window_size
|
81 |
+
|
82 |
+
@property
|
83 |
+
def min_resolution_step(self) -> int:
|
84 |
+
res = self.patch_size
|
85 |
+
if self.window_size is not None:
|
86 |
+
res *= self.window_size
|
87 |
+
return res
|
88 |
+
|
89 |
+
def make_preprocessor_external(self) -> Callable[[torch.Tensor], torch.Tensor]:
|
90 |
+
ret = self.input_conditioner
|
91 |
+
self.input_conditioner = nn.Identity()
|
92 |
+
return ret
|
93 |
+
|
94 |
+
def get_nearest_supported_resolution(self, height: int, width: int) -> Resolution:
|
95 |
+
height = int(round(height / self.min_resolution_step) * self.min_resolution_step)
|
96 |
+
width = int(round(width / self.min_resolution_step) * self.min_resolution_step)
|
97 |
+
|
98 |
+
height = max(height, self.min_resolution_step)
|
99 |
+
width = max(width, self.min_resolution_step)
|
100 |
+
|
101 |
+
return Resolution(height=height, width=width)
|
102 |
+
|
103 |
+
def switch_to_deploy(self):
|
104 |
+
fn = getattr(self.model, 'switch_to_deploy', None)
|
105 |
+
if fn is not None:
|
106 |
+
fn()
|
107 |
+
|
108 |
+
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
109 |
+
x = self.input_conditioner(x)
|
110 |
+
y = self.model.forward_features(x)
|
111 |
+
|
112 |
+
if isinstance(self.model, VisionTransformer):
|
113 |
+
patch_gen = getattr(self.model, "patch_generator", None)
|
114 |
+
if patch_gen is not None:
|
115 |
+
all_summary = y[:, : patch_gen.num_cls_tokens]
|
116 |
+
if self.summary_idxs is not None:
|
117 |
+
bb_summary = all_summary[:, self.summary_idxs]
|
118 |
+
else:
|
119 |
+
bb_summary = all_summary
|
120 |
+
all_feat = y[:, patch_gen.num_skip :]
|
121 |
+
elif self.model.global_pool == "avg":
|
122 |
+
all_summary = y[:, self.model.num_prefix_tokens :].mean(dim=1)
|
123 |
+
bb_summary = all_summary
|
124 |
+
all_feat = y
|
125 |
+
else:
|
126 |
+
all_summary = y[:, 0]
|
127 |
+
bb_summary = all_summary
|
128 |
+
all_feat = y[:, 1:]
|
129 |
+
elif isinstance(self.model, eradio_model.FasterViT):
|
130 |
+
_, f = y
|
131 |
+
all_feat = f.flatten(2).transpose(1, 2)
|
132 |
+
all_summary = all_feat.mean(dim=1)
|
133 |
+
bb_summary = all_summary
|
134 |
+
elif isinstance(y, (list, tuple)):
|
135 |
+
all_summary, all_feat = y
|
136 |
+
bb_summary = all_summary
|
137 |
+
else:
|
138 |
+
raise ValueError("Unsupported model type")
|
139 |
+
|
140 |
+
all_feat = all_feat.float()
|
141 |
+
ret = RadioOutput(bb_summary.flatten(1), all_feat).to(torch.float32)
|
142 |
+
if self.adaptors:
|
143 |
+
ret = dict(backbone=ret)
|
144 |
+
for name, adaptor in self.adaptors.items():
|
145 |
+
if all_summary.ndim == 3:
|
146 |
+
summary = all_summary[:, adaptor.head_idx]
|
147 |
+
else:
|
148 |
+
summary = all_summary
|
149 |
+
ada_input = AdaptorInput(images=x, summary=summary.float(), features=all_feat)
|
150 |
+
v = adaptor(ada_input).to(torch.float32)
|
151 |
+
ret[name] = v
|
152 |
+
|
153 |
+
return ret
|
154 |
+
|
155 |
+
|
156 |
+
def create_model_from_args(args) -> nn.Module:
|
157 |
+
in_chans = 3
|
158 |
+
if args.in_chans is not None:
|
159 |
+
in_chans = args.in_chans
|
160 |
+
elif args.input_size is not None:
|
161 |
+
in_chans = args.input_size[0]
|
162 |
+
|
163 |
+
# Skip weight initialization unless it's explicitly requested.
|
164 |
+
weight_init = args.model_kwargs.pop("weight_init", "skip")
|
165 |
+
|
166 |
+
model = create_model(
|
167 |
+
args.model,
|
168 |
+
pretrained=args.pretrained,
|
169 |
+
in_chans=in_chans,
|
170 |
+
num_classes=args.num_classes,
|
171 |
+
drop_rate=args.drop,
|
172 |
+
drop_path_rate=args.drop_path,
|
173 |
+
drop_block_rate=args.drop_block,
|
174 |
+
global_pool=args.gp,
|
175 |
+
bn_momentum=args.bn_momentum,
|
176 |
+
bn_eps=args.bn_eps,
|
177 |
+
scriptable=args.torchscript,
|
178 |
+
checkpoint_path=args.initial_checkpoint,
|
179 |
+
weight_init=weight_init,
|
180 |
+
**args.model_kwargs,
|
181 |
+
)
|
182 |
+
|
183 |
+
assert (
|
184 |
+
not args.cls_token_per_teacher or args.cpe_max_size is not None
|
185 |
+
), "CPE must be enabled for multiple CLS tokens!"
|
186 |
+
|
187 |
+
if args.cpe_max_size is not None:
|
188 |
+
enable_cpe(
|
189 |
+
model,
|
190 |
+
args.cpe_max_size,
|
191 |
+
num_cls_tokens=len(args.teachers) if args.cls_token_per_teacher else 1,
|
192 |
+
register_multiple=args.register_multiple,
|
193 |
+
)
|
194 |
+
|
195 |
+
return model
|
vit_patch_generator.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
@@ -224,12 +224,12 @@ class ViTPatchGenerator(nn.Module):
|
|
224 |
grid_xy.mul_(2).sub_(1)
|
225 |
|
226 |
pos_embed = F.grid_sample(
|
227 |
-
pos_embed.expand(batch_size, -1, -1, -1),
|
228 |
grid=grid_xy,
|
229 |
mode='bilinear',
|
230 |
padding_mode='zeros',
|
231 |
align_corners=True,
|
232 |
-
)
|
233 |
else:
|
234 |
# i_rows, i_cols = input_dims
|
235 |
# p_rows, p_cols = pos_embed.shape[2:]
|
|
|
1 |
+
# Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
|
2 |
#
|
3 |
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
# and proprietary rights in and to this software, related documentation
|
|
|
224 |
grid_xy.mul_(2).sub_(1)
|
225 |
|
226 |
pos_embed = F.grid_sample(
|
227 |
+
pos_embed.float().expand(batch_size, -1, -1, -1),
|
228 |
grid=grid_xy,
|
229 |
mode='bilinear',
|
230 |
padding_mode='zeros',
|
231 |
align_corners=True,
|
232 |
+
).to(pos_embed.dtype)
|
233 |
else:
|
234 |
# i_rows, i_cols = input_dims
|
235 |
# p_rows, p_cols = pos_embed.shape[2:]
|