deeplumiere commited on
Commit
22cca31
·
verified ·
1 Parent(s): bc7aa46

Upload fovit.py

Browse files
Files changed (1) hide show
  1. fovit.py +2037 -0
fovit.py ADDED
@@ -0,0 +1,2037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%writefile remsvit.py
2
+ ##WORKING MODEL##
3
+ import math
4
+ import os
5
+ import csv
6
+ import pickle
7
+ from datetime import datetime
8
+ from functools import lru_cache
9
+ import shutil
10
+ import numpy as np
11
+ from tqdm import tqdm
12
+
13
+ try:
14
+ import pynvml
15
+ except ImportError:
16
+ pynvml = None
17
+
18
+
19
+ def _get_writable_cache_dir():
20
+ """Returns a writable directory for caching: /kaggle/working on Kaggle, else cwd."""
21
+ kaggle_working = '/kaggle/working'
22
+ if os.path.isdir(kaggle_working) and os.access(kaggle_working, os.W_OK):
23
+ return kaggle_working
24
+ return os.getcwd()
25
+
26
+
27
+ import torch
28
+
29
+ torch.backends.cudnn.benchmark = True
30
+ torch.backends.cuda.matmul.allow_tf32 = True
31
+ torch.backends.cudnn.allow_tf32 = True
32
+ if hasattr(torch, 'set_float32_matmul_precision'):
33
+ torch.set_float32_matmul_precision('high')
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F
36
+ import torch.optim as optim
37
+ from torch.utils.data import DataLoader
38
+ from torch.optim.swa_utils import AveragedModel
39
+ from torchvision.transforms import v2
40
+ import torchvision
41
+ import torchvision.transforms as transforms
42
+ import os
43
+ import shutil
44
+ import urllib.request
45
+ import subprocess
46
+ import matplotlib.pyplot as plt
47
+ import seaborn as sns
48
+ import pandas as pd
49
+ import random
50
+
51
+
52
+ def set_seed(seed: int = 42):
53
+ """Make runs deterministic for reproducibility (CVPR requirement)."""
54
+ random.seed(seed)
55
+ np.random.seed(seed)
56
+ torch.manual_seed(seed)
57
+ torch.cuda.manual_seed(seed)
58
+ torch.cuda.manual_seed_all(seed)
59
+ # Note: deterministic=True and benchmark=False can slow down training.
60
+ # We leave benchmark=True here by default as ImageNet needs speed,
61
+ # but the seeds alone eliminate 99% of the variance from stochastic ops.
62
+ os.environ['PYTHONHASHSEED'] = str(seed)
63
+
64
+
65
+ class Config:
66
+ seed = 1992 # For reproducible runs
67
+ # Dataset
68
+ # For imagenet1k/imagenet100: set data_dir to the PARENT folder that contains
69
+ # imagenet_part_1/, imagenet_part_2/, ... OR a single folder with train/ and val/ sub-dirs.
70
+ # Example: data_dir = '/kaggle/input/imagenet-object-localization-challenge'
71
+ data_dir = "/home/admin/PycharmProjects/Deepresearch/data/archive"
72
+ dataset = 'imagenet1k'
73
+ num_classes = 1000 # cifar10=10, cifar100=100, imagenet1k=1000, imagenet100=100, tiny_imagenet=200
74
+ img_size = 224 # use 224 for imagenet1k/imagenet100
75
+ in_channels = 3
76
+ num_workers = 16 # WARNING: ImageNet-1K requires AT LEAST 16 workers, otherwise JPEG decoding caps out at ~120 img/s
77
+ prefetch_factor = 2
78
+
79
+ # Architecture
80
+ dim = 320
81
+ num_heads = 4 # 8 heads × 40 head_dim
82
+ depth = 4 # Shared blocks × 3 loops = 12 effective layers
83
+ mlp_ratio = 3.0
84
+ dropout = 0.1 # Increased for larger capacity
85
+ lrmin = 1e-5
86
+
87
+ # Recurrent Saliency (Pareto-optimal inference defaults)
88
+ k1_ratio = 0.35 # % of coarse patches to refine into medium
89
+ k2_ratio = 0.45 # % of medium patches to refine into fine
90
+
91
+ # Training
92
+ batch_size = 16 # Reduced from 128 to prevent VRAM swapping
93
+ accum_iter = 2 # Gradient accumulation steps
94
+ epochs = 50
95
+ accelerator = 'gpu' # Options: 'gpu' or 'tpu'
96
+ max_lr = 1e-4 # Scaled for smaller batch size
97
+ weight_decay = 0.1 # Reduced from 0.2: 0.05 is standard for tiny/small ViTs on ImageNet
98
+ label_smoothing = 0.1
99
+ ema_decay = 0.9999
100
+ grad_clip = 1.0
101
+ warmup_epochs = 5 # Short warmup, then cosine decay
102
+ drop_path_rate = 0.1 # Reduced from 0.2: small capacity ViTs underfit with high drop_path
103
+ use_mixup = True # MixUp/CutMix augmentation (disable for small datasets like VTAB-1k)
104
+ backbone_lr_scale = 1.0 # LR multiplier for backbone vs head (lower preserves pretrained features)
105
+ freeze_backbone_epochs = 0 # Freeze backbone for N epochs at start (for fine-tuning from pretrained)
106
+
107
+ save_path = 'eval_outputs/fovit224.pth'
108
+ pretrained_path = "eval_outputs/fovit224.pth"
109
+ checkpoint_path = 'fovit224_checkpoint_in1k_256.pth'
110
+ log_path = 'fovit224_log_in1k_256c10.csv'
111
+ resume = True
112
+ use_grad_checkpointing = False # Set to True if OOM
113
+ device = torch.device(
114
+ 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
115
+
116
+ def __init__(self):
117
+ # Auto-configure based on dataset to prevent dimension mismatches
118
+ ds = self.dataset.lower()
119
+ # if ds == 'imagenet1k':
120
+ # self.num_classes = 1000
121
+ # if self.img_size == 64: self.img_size = 224
122
+ # elif ds == 'imagenet100':
123
+ # self.num_classes = 100
124
+ # if self.img_size == 64: self.img_size = 224
125
+ # elif ds == 'tiny_imagenet':
126
+ # self.num_classes = 200
127
+ # elif ds == 'cifar10':
128
+ # self.num_classes = 10
129
+ # elif ds.startswith('vtab_'):
130
+ # # num_classes will be set dynamically by DataFactory
131
+ # if self.img_size == 64: self.img_size = 128
132
+
133
+ # Convert percentages to absolute patch counts based on image resolution
134
+ # N_c = (self.img_size // 16) ** 2
135
+ # self.K1 = max(1, int(N_c * self.k1_ratio))
136
+ # self.K2 = max(1, int((self.K1 * 4) * self.k2_ratio))
137
+
138
+ @property
139
+ def K1(self):
140
+ N_c = (self.img_size // 16) ** 2
141
+ return max(1, int(N_c * self.k1_ratio))
142
+
143
+ @property
144
+ def K2(self):
145
+ return max(1, int((self.K1 * 4) * self.k2_ratio))
146
+
147
+
148
+ def count_parameters(model: nn.Module) -> int:
149
+ n = sum(p.numel() for p in model.parameters() if p.requires_grad)
150
+ print(f" Trainable parameters: {n:,}")
151
+ return n
152
+
153
+
154
+ def get_energy(handle):
155
+ if handle is None or pynvml is None: return 0.0
156
+ try:
157
+ return pynvml.nvmlDeviceGetTotalEnergyConsumption(handle) / 1000.0
158
+ except Exception:
159
+ return 0.0
160
+
161
+
162
+ def generate_live_plots(csv_path, save_prefix="fovit_metrics"):
163
+ try:
164
+ df = pd.read_csv(csv_path)
165
+ if len(df) < 2: return
166
+
167
+ # High quality lab style
168
+ sns.set_theme(style="whitegrid", context="talk", font_scale=1.2)
169
+ plt.rcParams.update({
170
+ "figure.dpi": 300,
171
+ "figure.facecolor": "white",
172
+ "savefig.facecolor": "white",
173
+ "axes.facecolor": "white",
174
+ "axes.linewidth": 2.0,
175
+ "axes.edgecolor": "#333333",
176
+ "grid.color": "#e0e0e0",
177
+ "grid.linestyle": "--",
178
+ "grid.alpha": 0.7,
179
+ "axes.labelsize": 14,
180
+ "xtick.labelsize": 12,
181
+ "ytick.labelsize": 12,
182
+ "font.family": "sans-serif",
183
+ "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
184
+ })
185
+
186
+ # Plot 1: Train Loss (Separate PDF)
187
+ plt.figure(figsize=(10, 6))
188
+ ax1 = sns.lineplot(data=df, x='Epoch', y='Train_Loss', color='#D62728', linewidth=2.5, marker='o', markersize=4,
189
+ markeredgecolor='white')
190
+ ax1.set_xlabel('Training Epoch', fontweight='bold')
191
+ ax1.set_ylabel('Cross-Entropy Loss', fontweight='bold')
192
+ ax1.fill_between(df['Epoch'], df['Train_Loss'], alpha=0.1, color='#D62728')
193
+ plt.tight_layout()
194
+ plt.savefig(f"{save_prefix}_loss.pdf", bbox_inches='tight', facecolor='white')
195
+ plt.close()
196
+
197
+ # Plot 2: Accuracy (Separate PDF)
198
+ plt.figure(figsize=(10, 6))
199
+ ax2 = sns.lineplot(data=df, x='Epoch', y='Test_Acc', color='#1F77B4', label='Eval Top-1 Accuracy', linewidth=2,
200
+ alpha=0.7)
201
+ sns.lineplot(data=df, x='Epoch', y='Best_Acc', ax=ax2, color='#FF7F0E', label='Best Top-1 Accuracy',
202
+ linewidth=2.5, linestyle='--')
203
+ ax2.set_xlabel('Training Epoch', fontweight='bold')
204
+ ax2.set_ylabel('Accuracy (%)', fontweight='bold')
205
+ ax2.legend(loc='lower right', frameon=True, fancybox=True, shadow=True, borderpad=1)
206
+ plt.tight_layout()
207
+ plt.savefig(f"{save_prefix}_accuracy.pdf", bbox_inches='tight', facecolor='white')
208
+ plt.close()
209
+
210
+ # Plot 3: Learning Rate (Separate PDF)
211
+ plt.figure(figsize=(10, 6))
212
+ ax3 = sns.lineplot(data=df, x='Epoch', y='LR', color='#2CA02C', linewidth=2.5)
213
+ ax3.set_xlabel('Training Epoch', fontweight='bold')
214
+ ax3.set_ylabel('Learning Rate', fontweight='bold')
215
+ ax3.set_yscale('log')
216
+ ax3.fill_between(df['Epoch'], df['LR'], alpha=0.1, color='#2CA02C')
217
+ plt.tight_layout()
218
+ plt.savefig(f"{save_prefix}_lr.pdf", bbox_inches='tight', facecolor='white')
219
+ plt.close()
220
+
221
+ # Plot 4: Recurrence Losses (Separate PDF)
222
+ if 'Loss_L0' in df.columns:
223
+ plt.figure(figsize=(10, 6))
224
+ ax4 = sns.lineplot(data=df, x='Epoch', y='Loss_L0', color='#1F77B4', label='Loop 0 (Coarse)', linewidth=2.5)
225
+ if 'Loss_L1' in df.columns:
226
+ sns.lineplot(data=df, x='Epoch', y='Loss_L1', ax=ax4, color='#FF7F0E', label='Loop 1 (Medium)',
227
+ linewidth=2.5)
228
+ if 'Loss_L2' in df.columns:
229
+ sns.lineplot(data=df, x='Epoch', y='Loss_L2', ax=ax4, color='#2CA02C', label='Loop 2 (Fine)',
230
+ linewidth=2.5)
231
+ ax4.set_xlabel('Training Epoch', fontweight='bold')
232
+ ax4.set_ylabel('Cross-Entropy Loss', fontweight='bold')
233
+ ax4.legend(loc='upper right', frameon=True, fancybox=True, shadow=True, borderpad=1)
234
+ plt.tight_layout()
235
+ plt.savefig(f"{save_prefix}_recurrence.pdf", bbox_inches='tight', facecolor='white')
236
+ plt.close()
237
+
238
+ # Plot 5: Entropy Loss (Separate PDF)
239
+ if 'Entropy_Loss' in df.columns:
240
+ plt.figure(figsize=(10, 6))
241
+ ax5 = sns.lineplot(data=df, x='Epoch', y='Entropy_Loss', color='#9467bd', linewidth=2.5)
242
+ ax5.set_xlabel('Training Epoch', fontweight='bold')
243
+ ax5.set_ylabel('Saliency Entropy', fontweight='bold')
244
+ ax5.fill_between(df['Epoch'], df['Entropy_Loss'], alpha=0.1, color='#9467bd')
245
+ plt.tight_layout()
246
+ plt.savefig(f"{save_prefix}_entropy.pdf", bbox_inches='tight', facecolor='white')
247
+ plt.close()
248
+ except Exception as e:
249
+ print(f"Failed to generate plots: {e}")
250
+
251
+
252
+ # ==============================================================================
253
+ # DATA FACTORY
254
+ # ==============================================================================
255
+ try:
256
+ import cv2
257
+
258
+ _HAS_CV2 = True
259
+ except ImportError:
260
+ _HAS_CV2 = False
261
+
262
+ from PIL import Image
263
+
264
+
265
+ def _fast_loader(path):
266
+ """OpenCV-accelerated image loader with PIL fallback."""
267
+ if _HAS_CV2:
268
+ img = cv2.imread(path)
269
+ if img is not None:
270
+ return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
271
+ return Image.open(path).convert('RGB')
272
+
273
+
274
+ class FastImageFolder(torch.utils.data.Dataset):
275
+ """
276
+ High-performance ImageNet loader:
277
+ - Scans multiple root directories with unified class index.
278
+ - Caches the sample manifest (path, target) to disk on first run.
279
+ - Uses OpenCV for fast JPEG decoding with PIL fallback.
280
+ """
281
+ VALID_EXTS = {'.png', '.jpg', '.jpeg', '.JPEG', '.webp'}
282
+
283
+ def __init__(self, root_list, transform=None, cache_path=None):
284
+ if isinstance(root_list, str):
285
+ root_list = [root_list]
286
+ root_list = [r for r in root_list if os.path.isdir(r)]
287
+ if not root_list:
288
+ raise ValueError(f"No valid directories found in: {root_list}")
289
+ self.transform = transform
290
+
291
+ if cache_path is None:
292
+ # Always write cache to a writable dir (Kaggle input is read-only)
293
+ cache_dir = _get_writable_cache_dir()
294
+ cache_key = os.path.basename(os.path.dirname(root_list[0]))
295
+ cache_path = os.path.join(cache_dir, f'.fif_cache_{cache_key}.pkl')
296
+
297
+ if os.path.exists(cache_path):
298
+ with open(cache_path, 'rb') as f:
299
+ cached = pickle.load(f)
300
+ self.classes = cached['classes']
301
+ self.class_to_idx = cached['class_to_idx']
302
+ self.samples = cached['samples']
303
+ print(f"[FastImageFolder] Loaded {len(self.samples):,} samples from cache.")
304
+ else:
305
+ print(f"[FastImageFolder] Building sample manifest (first run only)...")
306
+ self.classes, self.class_to_idx = self._find_classes(root_list)
307
+ self.samples = self._make_dataset(root_list)
308
+ try:
309
+ with open(cache_path, 'wb') as f:
310
+ pickle.dump({'classes': self.classes, 'class_to_idx': self.class_to_idx, 'samples': self.samples},
311
+ f, protocol=4)
312
+ print(f"[FastImageFolder] Cached {len(self.samples):,} samples to {cache_path}")
313
+ except OSError:
314
+ pass
315
+
316
+ def _find_classes(self, root_list):
317
+ classes = set()
318
+ for root in root_list:
319
+ classes.update(d.name for d in os.scandir(root) if d.is_dir())
320
+ classes = sorted(classes)
321
+ return classes, {c: i for i, c in enumerate(classes)}
322
+
323
+ def _make_dataset(self, root_list):
324
+ samples = []
325
+ for root in root_list:
326
+ for entry in os.scandir(root):
327
+ if not entry.is_dir(): continue
328
+ cls_idx = self.class_to_idx.get(entry.name)
329
+ if cls_idx is None: continue
330
+ for fentry in os.scandir(entry.path):
331
+ if os.path.splitext(fentry.name)[1].lower() in self.VALID_EXTS:
332
+ samples.append((fentry.path, cls_idx))
333
+ return samples
334
+
335
+ def __len__(self):
336
+ return len(self.samples)
337
+
338
+ def __getitem__(self, index):
339
+ path, target = self.samples[index]
340
+ img = _fast_loader(path)
341
+ if self.transform is not None:
342
+ img = self.transform(img)
343
+ return img, target
344
+
345
+
346
+ class DataFactory:
347
+ STATS = {
348
+ 'cifar10': ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
349
+ 'cifar100': ((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2762)),
350
+ 'svhn': ((0.4377, 0.4438, 0.4728), (0.1980, 0.2010, 0.1970)),
351
+ 'tiny_imagenet': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
352
+ 'flowers102': ((0.4330, 0.3819, 0.2964), (0.2485, 0.2201, 0.2319)),
353
+ 'imagenet1k': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
354
+ 'imagenet100': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
355
+ }
356
+
357
+ @classmethod
358
+ def calculate_dataset_stats(cls, dataset, batch_size=256, num_workers=4):
359
+ print("Calculating dataset mean and std dynamically (this may take a moment)...")
360
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)
361
+ sum_ = None
362
+ sum_of_squares = None
363
+ total_pixels = 0
364
+
365
+ for images, _ in loader:
366
+ C = images.size(1)
367
+ if sum_ is None:
368
+ sum_ = torch.zeros(C)
369
+ sum_of_squares = torch.zeros(C)
370
+
371
+ sum_ += images.sum(dim=[0, 2, 3])
372
+ sum_of_squares += (images ** 2).sum(dim=[0, 2, 3])
373
+ total_pixels += images.size(0) * images.size(2) * images.size(3)
374
+
375
+ mean = sum_ / total_pixels
376
+ var = (sum_of_squares / total_pixels) - (mean ** 2)
377
+ std = torch.sqrt(torch.clamp(var, min=1e-6))
378
+ return mean.tolist(), std.tolist()
379
+
380
+ @classmethod
381
+ def _get_raw_dataset(cls, ds, config, transform):
382
+ if ds == 'cifar10':
383
+ return torchvision.datasets.CIFAR10(config.data_dir, train=True, download=True, transform=transform)
384
+ elif ds == 'cifar100':
385
+ return torchvision.datasets.CIFAR100(config.data_dir, train=True, download=True, transform=transform)
386
+ elif ds == 'svhn':
387
+ return torchvision.datasets.SVHN(config.data_dir, split='train', download=True, transform=transform)
388
+ elif ds == 'tiny_imagenet':
389
+ train_dir, _ = cls.prepare_tiny_imagenet(config.data_dir)
390
+ return torchvision.datasets.ImageFolder(train_dir, transform=transform)
391
+ elif ds in ('imagenet1k', 'imagenet100'):
392
+ train_dir = os.path.join(config.data_dir, 'train')
393
+ if os.path.exists(train_dir):
394
+ cache_dir = _get_writable_cache_dir()
395
+ return FastImageFolder([train_dir], transform=transform,
396
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
397
+ prefix = 'imagenet' if ds == 'imagenet1k' else 'imagenet100'
398
+ train_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'train') for i in range(1, 5)]
399
+ train_roots = [r for r in train_roots if os.path.exists(r)]
400
+ cache_dir = _get_writable_cache_dir()
401
+ return FastImageFolder(train_roots, transform=transform,
402
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
403
+ elif ds == 'flowers102':
404
+ return torchvision.datasets.Flowers102(config.data_dir, split='train', download=True, transform=transform)
405
+ else:
406
+ raise ValueError(f"Unknown dataset {ds}")
407
+
408
+ @staticmethod
409
+ def prepare_tiny_imagenet(input_dir):
410
+ is_master = True
411
+
412
+ working_dir = "/kaggle/working/tiny_imagenet_data"
413
+ base_dir = os.path.join(working_dir, "tiny-imagenet-200")
414
+
415
+ # Handle Kaggle input path logic
416
+ kaggle_src = os.path.join(input_dir, "tiny-imagenet-200")
417
+ if not os.path.exists(kaggle_src) and "tiny-imagenet-200" in input_dir:
418
+ kaggle_src = input_dir
419
+
420
+ if os.path.exists(kaggle_src):
421
+ # OPTIMIZATION 1: Zero-Copy Training Data
422
+ # Read the training data directly from the read-only Kaggle input.
423
+ # PyTorch's ImageFolder works perfectly fine pointing to read-only directories.
424
+ train_dir = os.path.join(kaggle_src, 'train')
425
+
426
+ # OPTIMIZATION 2: Symlink Validation Data
427
+ # Instead of copying, we create empty folders and map virtual symbolic
428
+ # links to the read-only files. This takes milliseconds.
429
+ val_dir = os.path.join(base_dir, 'val')
430
+
431
+ if is_master and not os.path.exists(val_dir):
432
+ print("Creating fast symlinks for validation set...")
433
+ os.makedirs(val_dir, exist_ok=True)
434
+
435
+ val_images_src = os.path.join(kaggle_src, 'val', 'images')
436
+ val_annotations = os.path.join(kaggle_src, 'val', 'val_annotations.txt')
437
+
438
+ with open(val_annotations, 'r') as f:
439
+ lines = f.readlines()
440
+
441
+ # Pre-create the 200 class directories (faster than doing it in the image loop)
442
+ unique_classes = set(line.strip().split('\t')[1] for line in lines)
443
+ for class_id in unique_classes:
444
+ os.makedirs(os.path.join(val_dir, class_id), exist_ok=True)
445
+
446
+ # Create symlinks mapping to the read-only original files
447
+ for line in lines:
448
+ img_name, class_id = line.strip().split('\t')[:2]
449
+ src_img = os.path.join(val_images_src, img_name)
450
+ dst_img = os.path.join(val_dir, class_id, img_name)
451
+
452
+ if not os.path.exists(dst_img):
453
+ os.symlink(src_img, dst_img)
454
+
455
+ else:
456
+ # Fallback if the dataset isn't mounted and we MUST download it
457
+ train_dir = os.path.join(base_dir, 'train')
458
+ val_dir = os.path.join(base_dir, 'val')
459
+
460
+ if is_master and not os.path.exists(base_dir):
461
+ os.makedirs(working_dir, exist_ok=True)
462
+ print("Downloading TinyImageNet...")
463
+ zip_path = os.path.join(working_dir, "tiny.zip")
464
+ urllib.request.urlretrieve("http://cs231n.stanford.edu/tiny-imagenet-200.zip", zip_path)
465
+
466
+ # OPTIMIZATION 3: Native Extraction
467
+ # System `unzip` is 10x+ faster than Python's `zipfile` module for small files
468
+ print("Extracting via system unzip...")
469
+ subprocess.run(['unzip', '-q', zip_path, '-d', working_dir], check=True)
470
+ os.remove(zip_path)
471
+
472
+ # Restructure downloaded val data
473
+ print("Restructuring downloaded validation set...")
474
+ val_images_dir = os.path.join(val_dir, 'images')
475
+ val_annotations = os.path.join(val_dir, 'val_annotations.txt')
476
+
477
+ with open(val_annotations, 'r') as f:
478
+ lines = f.readlines()
479
+
480
+ unique_classes = set(line.strip().split('\t')[1] for line in lines)
481
+ for class_id in unique_classes:
482
+ os.makedirs(os.path.join(val_dir, class_id), exist_ok=True)
483
+
484
+ for line in lines:
485
+ img_name, class_id = line.strip().split('\t')[:2]
486
+ src_img = os.path.join(val_images_dir, img_name)
487
+ dst_img = os.path.join(val_dir, class_id, img_name)
488
+ if os.path.exists(src_img):
489
+ os.rename(src_img, dst_img)
490
+
491
+ shutil.rmtree(val_images_dir)
492
+ os.remove(val_annotations)
493
+
494
+ return train_dir, val_dir
495
+
496
+ @classmethod
497
+ def get_dataloaders(cls, config):
498
+ ds = config.dataset.lower()
499
+
500
+ if ds.startswith('vtab_'):
501
+ from vtab_datasets import download_vtab, VTABDataFactory
502
+ task_name = ds.split('vtab_')[1]
503
+ vtab_dir = download_vtab(config.data_dir)
504
+ train_loader, test_loader, num_classes = VTABDataFactory.get_dataloaders(
505
+ task_name, vtab_dir, img_size=config.img_size, batch_size=config.batch_size,
506
+ num_workers=config.num_workers,
507
+ )
508
+ config.num_classes = num_classes # Dynamically set num classes
509
+ return train_loader, test_loader, len(train_loader.dataset), len(test_loader.dataset)
510
+
511
+ os.makedirs(config.data_dir, exist_ok=True)
512
+
513
+ img_size = config.img_size
514
+
515
+ if ds not in cls.STATS:
516
+ print(f"Dataset '{ds}' stats not found. Calculating dynamically...")
517
+ temp_tf = transforms.Compose([
518
+ transforms.Resize((img_size, img_size)),
519
+ transforms.ToTensor()
520
+ ])
521
+ temp_dataset = cls._get_raw_dataset(ds, config, temp_tf)
522
+ mean, std = cls.calculate_dataset_stats(temp_dataset, num_workers=config.num_workers)
523
+ cls.STATS[ds] = (mean, std)
524
+ print(f"Calculated stats for '{ds}':\n Mean: {mean}\n Std: {std}")
525
+
526
+ mean, std = cls.STATS[ds]
527
+
528
+ padding = max(4, img_size // 8)
529
+
530
+ train_tf = transforms.Compose([
531
+ transforms.Resize((img_size, img_size)),
532
+ transforms.RandomCrop(img_size, padding=padding, padding_mode='reflect'),
533
+ transforms.RandomHorizontalFlip(),
534
+ transforms.RandAugment(num_ops=2, magnitude=9),
535
+ transforms.ToTensor(),
536
+ transforms.Normalize(mean, std)
537
+ ])
538
+ test_tf = transforms.Compose([
539
+ transforms.Resize((img_size, img_size)),
540
+ transforms.ToTensor(),
541
+ transforms.Normalize(mean, std)
542
+ ])
543
+
544
+ if ds == 'cifar10':
545
+ trainset = torchvision.datasets.CIFAR10(config.data_dir, train=True, download=True, transform=train_tf)
546
+ testset = torchvision.datasets.CIFAR10(config.data_dir, train=False, download=True, transform=test_tf)
547
+ elif ds == 'cifar100':
548
+ trainset = torchvision.datasets.CIFAR100(config.data_dir, train=True, download=True, transform=train_tf)
549
+ testset = torchvision.datasets.CIFAR100(config.data_dir, train=False, download=True, transform=test_tf)
550
+ elif ds == 'svhn':
551
+ trainset = torchvision.datasets.SVHN(config.data_dir, split='train', download=True, transform=train_tf)
552
+ testset = torchvision.datasets.SVHN(config.data_dir, split='test', download=True, transform=test_tf)
553
+ elif ds == 'tiny_imagenet':
554
+ train_dir, val_dir = cls.prepare_tiny_imagenet(config.data_dir)
555
+ trainset = torchvision.datasets.ImageFolder(train_dir, transform=train_tf)
556
+ testset = torchvision.datasets.ImageFolder(val_dir, transform=test_tf)
557
+ elif ds in ('imagenet1k', 'imagenet100'):
558
+ in1k_train_tf = transforms.Compose([
559
+ transforms.RandomResizedCrop(img_size),
560
+ transforms.RandomHorizontalFlip(),
561
+ transforms.RandAugment(num_ops=2, magnitude=9),
562
+ transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
563
+ transforms.ToTensor(),
564
+ transforms.Normalize(mean, std),
565
+ transforms.RandomErasing(p=0.25)
566
+ ])
567
+ in1k_test_tf = transforms.Compose([
568
+ transforms.Resize(int(img_size * 1.14)),
569
+ transforms.CenterCrop(img_size),
570
+ transforms.ToTensor(),
571
+ transforms.Normalize(mean, std)
572
+ ])
573
+
574
+ train_dir = os.path.join(config.data_dir, 'train')
575
+ val_dir = os.path.join(config.data_dir, 'val')
576
+ cache_dir = _get_writable_cache_dir()
577
+ if os.path.exists(train_dir):
578
+ trainset = FastImageFolder([train_dir], transform=in1k_train_tf,
579
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
580
+ testset = FastImageFolder([val_dir], transform=in1k_test_tf,
581
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_val.pkl'))
582
+ else:
583
+ prefix = 'imagenet' if ds == 'imagenet1k' else 'imagenet100'
584
+ train_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'train') for i in range(1, 5)]
585
+ val_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'val') for i in range(1, 5)]
586
+ valid_train = [r for r in train_roots if os.path.exists(r)]
587
+ valid_val = [r for r in val_roots if os.path.exists(r)]
588
+ if not valid_train:
589
+ raise FileNotFoundError(
590
+ f"No ImageNet directory partitions found at '{config.data_dir}'.\n"
591
+ f"If running locally, please edit Config.data_dir = 'data' and Config.dataset = 'cifar100' or 'tiny_imagenet'."
592
+ )
593
+ trainset = FastImageFolder(valid_train, transform=in1k_train_tf,
594
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
595
+ testset = FastImageFolder(valid_val, transform=in1k_test_tf,
596
+ cache_path=os.path.join(cache_dir, f'.fif_{ds}_val.pkl'))
597
+ elif ds == 'flowers102':
598
+ trainset = torchvision.datasets.Flowers102(config.data_dir, split='train', download=True,
599
+ transform=train_tf)
600
+ testset = torchvision.datasets.Flowers102(config.data_dir, split='test', download=True, transform=test_tf)
601
+ else:
602
+ raise ValueError(f"Unknown dataset {ds}")
603
+
604
+ persistent = config.num_workers > 0
605
+ train_loader = DataLoader(trainset, batch_size=config.batch_size, shuffle=True,
606
+ num_workers=config.num_workers, prefetch_factor=config.prefetch_factor,
607
+ pin_memory=True, drop_last=True, persistent_workers=persistent)
608
+ test_loader = DataLoader(testset, batch_size=config.batch_size, shuffle=False,
609
+ num_workers=config.num_workers, prefetch_factor=config.prefetch_factor,
610
+ pin_memory=True, persistent_workers=persistent)
611
+ return train_loader, test_loader, len(trainset), len(testset)
612
+
613
+
614
+ # ==============================================================================
615
+ # ARCHITECTURE MODULES
616
+ # ==============================================================================
617
+ class ChannelAttention(nn.Module):
618
+ """Channel attention with reduction ratio — negligible parameter overhead."""
619
+
620
+ def __init__(self, dim, reduction=16):
621
+ super().__init__()
622
+ self.pool = nn.AdaptiveAvgPool2d(1)
623
+ self.fc = nn.Sequential(
624
+ nn.Linear(dim, dim // reduction, bias=False),
625
+ nn.GELU(),
626
+ nn.Linear(dim // reduction, dim, bias=False),
627
+ nn.Sigmoid()
628
+ )
629
+
630
+ def forward(self, x):
631
+ B, C, _, _ = x.shape
632
+ w = self.pool(x).view(B, C)
633
+ w = self.fc(w).view(B, C, 1, 1)
634
+ return x * w
635
+
636
+
637
+ class ConvBlock(nn.Module):
638
+ def __init__(self, dim):
639
+ super().__init__()
640
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
641
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
642
+ self.pwconv1 = nn.Linear(dim, 4 * dim)
643
+ self.act = nn.GELU()
644
+ self.pwconv2 = nn.Linear(4 * dim, dim)
645
+ self.se = ChannelAttention(dim)
646
+
647
+ def forward(self, x):
648
+ input = x
649
+ x = self.dwconv(x)
650
+ x = x.permute(0, 2, 3, 1) # NCHW -> NHWC
651
+ x = self.norm(x)
652
+ x = self.pwconv1(x)
653
+ x = self.act(x)
654
+ x = self.pwconv2(x)
655
+ x = x.permute(0, 3, 1, 2) # NHWC -> NCHW
656
+ x = self.se(x)
657
+ return input + x
658
+
659
+
660
+ class FeaturePyramid(nn.Module):
661
+ def __init__(self, in_channels, channels):
662
+ super().__init__()
663
+ c1, c2, c3 = channels
664
+ self.stem = nn.Sequential(
665
+ nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False),
666
+ nn.BatchNorm2d(64),
667
+ nn.GELU(),
668
+ ConvBlock(64)
669
+ )
670
+ self.down1 = nn.Sequential(
671
+ nn.Conv2d(64, c3, kernel_size=2, stride=2), # 16x16
672
+ ConvBlock(c3)
673
+ )
674
+ self.down2 = nn.Sequential(
675
+ nn.Conv2d(c3, c2, kernel_size=2, stride=2), # 8x8
676
+ ConvBlock(c2)
677
+ )
678
+ self.down3 = nn.Sequential(
679
+ nn.Conv2d(c2, c1, kernel_size=2, stride=2), # 4x4
680
+ ConvBlock(c1)
681
+ )
682
+
683
+ def forward(self, x):
684
+ if x.is_cuda and not x.is_contiguous(memory_format=torch.channels_last):
685
+ x = x.to(memory_format=torch.channels_last)
686
+ x = self.stem(x)
687
+ f_fine = self.down1(x)
688
+ f_medium = self.down2(f_fine)
689
+ f_coarse = self.down3(f_medium)
690
+ return f_coarse, f_medium, f_fine
691
+
692
+
693
+ class DropPath(nn.Module):
694
+ """Simple inline DropPath to avoid silent degradation if timm is missing."""
695
+
696
+ def __init__(self, drop_prob=0.0):
697
+ super().__init__()
698
+ self.drop_prob = drop_prob
699
+
700
+ def forward(self, x):
701
+ if not self.training or self.drop_prob == 0.:
702
+ return x
703
+ keep = 1 - self.drop_prob
704
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
705
+ mask = x.new_empty(shape).bernoulli_(keep).div_(keep)
706
+ return x * mask
707
+
708
+
709
+ class LoopAdjuster(nn.Module):
710
+ def __init__(self, dim, r=16):
711
+ super().__init__()
712
+ self.down = nn.Linear(dim, r, bias=False)
713
+ self.act = nn.GELU()
714
+ self.up = nn.Linear(r, dim, bias=False)
715
+ nn.init.zeros_(self.up.weight)
716
+
717
+ def forward(self, x):
718
+ return self.up(self.act(self.down(x)))
719
+
720
+
721
+ class AttentionBlock(nn.Module):
722
+ def __init__(self, dim, num_heads, mlp_ratio=4.0, dropout=0.0, drop_path=0.0):
723
+ super().__init__()
724
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
725
+
726
+ self.heads = num_heads
727
+ self.head_dim = dim // num_heads
728
+ self.drop_p = dropout
729
+
730
+ self.norm1 = nn.LayerNorm(dim, eps=1e-6)
731
+ self.qkv = nn.Linear(dim, 3 * dim, bias=True)
732
+ self.proj = nn.Linear(dim, dim)
733
+ self.proj_drop = nn.Dropout(dropout)
734
+ self.msa_adjusters = nn.ModuleList([LoopAdjuster(dim) for _ in range(3)])
735
+
736
+ self.norm2 = nn.LayerNorm(dim, eps=1e-6)
737
+ mlp_dim = int(dim * mlp_ratio)
738
+ self.mlp = nn.Sequential(
739
+ nn.Linear(dim, mlp_dim),
740
+ nn.GELU(),
741
+ nn.Dropout(dropout),
742
+ nn.Linear(mlp_dim, dim),
743
+ nn.Dropout(dropout)
744
+ )
745
+ self.mlp_adjusters = nn.ModuleList([LoopAdjuster(dim) for _ in range(3)])
746
+
747
+ def forward(self, x, sin, cos, loop_idx, cls_only=False):
748
+ if cls_only:
749
+ normed_x = self.norm1(x)
750
+ B, N, C = normed_x.shape
751
+ # Q only for CLS token (B, 1, C); K, V for all tokens (B, N, C)
752
+ q_lin = F.linear(normed_x[:, 0:1], self.qkv.weight[:C], self.qkv.bias[:C] if self.qkv.bias is not None else None)
753
+ kv_lin = F.linear(normed_x, self.qkv.weight[C:], self.qkv.bias[C:] if self.qkv.bias is not None else None)
754
+
755
+ q = q_lin.reshape(B, 1, self.heads, self.head_dim).permute(0, 2, 1, 3)
756
+ kv = kv_lin.reshape(B, N, 2, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
757
+ k, v = kv[0], kv[1]
758
+
759
+ q = apply_rotary_pos_emb(q, sin[:, 0:1], cos[:, 0:1]).to(v.dtype).contiguous()
760
+ k = apply_rotary_pos_emb(k, sin, cos).to(v.dtype).contiguous()
761
+ v = v.contiguous()
762
+
763
+ attn_out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.drop_p if self.training else 0.0)
764
+ attn_out = attn_out.transpose(1, 2).reshape(B, 1, C)
765
+
766
+ x_cls = x[:, 0:1]
767
+ msa_out = self.proj_drop(self.proj(attn_out)) + self.msa_adjusters[loop_idx](x_cls)
768
+ x_cls = x_cls + self.drop_path(msa_out)
769
+
770
+ normed_cls = self.norm2(x_cls)
771
+ mlp_out = self.mlp(normed_cls) + self.mlp_adjusters[loop_idx](normed_cls)
772
+ return x_cls + self.drop_path(mlp_out)
773
+
774
+ normed_x = self.norm1(x)
775
+ qkv = self.qkv(normed_x)
776
+ B, N, C = normed_x.shape
777
+ qkv = qkv.reshape(B, N, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
778
+ q, k, v = qkv[0], qkv[1], qkv[2]
779
+
780
+ q = apply_rotary_pos_emb(q, sin, cos).to(v.dtype).contiguous()
781
+ k = apply_rotary_pos_emb(k, sin, cos).to(v.dtype).contiguous()
782
+ v = v.contiguous()
783
+
784
+ attn_out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.drop_p if self.training else 0.0)
785
+
786
+ attn_out = attn_out.transpose(1, 2).reshape(B, N, C)
787
+
788
+ msa_out = self.proj_drop(self.proj(attn_out)) + self.msa_adjusters[loop_idx](x)
789
+ x = x + self.drop_path(msa_out)
790
+
791
+ normed_x = self.norm2(x)
792
+ mlp_out = self.mlp(normed_x) + self.mlp_adjusters[loop_idx](normed_x)
793
+ x = x + self.drop_path(mlp_out)
794
+ return x
795
+
796
+
797
+ class RoPE2D(nn.Module):
798
+ def __init__(self, head_dim, base=10000.0):
799
+ super().__init__()
800
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim // 2, 2).float() / (head_dim // 2)))
801
+ self.register_buffer('inv_freq', inv_freq)
802
+
803
+ def forward(self, coords):
804
+ x, y = coords[..., 0], coords[..., 1]
805
+ freqs_x = x.unsqueeze(-1) * self.inv_freq
806
+ freqs_y = y.unsqueeze(-1) * self.inv_freq
807
+ emb_x = torch.cat((freqs_x, freqs_x), dim=-1)
808
+ emb_y = torch.cat((freqs_y, freqs_y), dim=-1)
809
+ emb = torch.cat((emb_x, emb_y), dim=-1)
810
+ return torch.sin(emb), torch.cos(emb)
811
+
812
+
813
+ def apply_rotary_pos_emb(x, sin, cos):
814
+ sin = sin.unsqueeze(1)
815
+ cos = cos.unsqueeze(1)
816
+ q = x.shape[-1] // 4
817
+ x_rot = torch.cat([-x[..., q:2*q], x[..., :q], -x[..., 3*q:], x[..., 2*q:3*q]], dim=-1)
818
+ return torch.addcmul(x * cos, x_rot, sin)
819
+
820
+
821
+ def differentiable_topk(scores, K, tau=1.0, training=False):
822
+ """
823
+ CVPR-standard Perturbed Top-K with Straight-Through Estimator.
824
+ Provides gradients to all elements via Gumbel-Softmax relaxation.
825
+ Bypasses STE computation during inference (training=False) for speed.
826
+ """
827
+ B, N = scores.shape
828
+ if training:
829
+ gumbels = -torch.empty_like(scores).exponential_().log()
830
+ perturbed = scores + gumbels
831
+ else:
832
+ perturbed = scores
833
+
834
+ # Use argsort to get both top and bottom K in a single pass, avoiding slow kthvalue
835
+ sorted_idx = torch.argsort(perturbed, dim=-1, descending=True)
836
+ topk_idx = sorted_idx[..., :K]
837
+
838
+ if N > K:
839
+ botk_idx = sorted_idx[..., K:]
840
+ else:
841
+ botk_idx = None
842
+
843
+ if training:
844
+ threshold = perturbed.gather(-1, topk_idx[..., -1:])
845
+ soft_mask = torch.sigmoid((perturbed - threshold) / tau)
846
+ hard_mask = torch.zeros_like(scores).scatter(-1, topk_idx, 1.0)
847
+ mask = hard_mask - soft_mask.detach() + soft_mask
848
+ else:
849
+ mask = None
850
+
851
+ return mask, topk_idx, botk_idx
852
+
853
+
854
+ def get_fvcore_flops(model, config, device=None):
855
+ """
856
+ Profile full forward pass FLOPs / MACs using fvcore FlopCountAnalysis.
857
+ Counts 1 MAC = 1 FLOP as per fvcore standard.
858
+ """
859
+ try:
860
+ from fvcore.nn import FlopCountAnalysis
861
+ if device is None:
862
+ device = next(model.parameters()).device
863
+ dummy = torch.randn(1, config.in_channels, config.img_size, config.img_size, device=device)
864
+
865
+ class _FullEval(nn.Module):
866
+ def __init__(self, m):
867
+ super().__init__()
868
+ self.m = m
869
+
870
+ def forward(self, x):
871
+ return self.m.forward_eval(x, max_loops=3)[0]
872
+
873
+ was_training = model.training
874
+ model.eval()
875
+ with torch.no_grad():
876
+ flops = FlopCountAnalysis(_FullEval(model), dummy).total()
877
+ if was_training:
878
+ model.train()
879
+ return float(flops)
880
+ except Exception:
881
+ return 0.0
882
+
883
+
884
+ class FoViT(nn.Module):
885
+ def __init__(self, config: Config):
886
+ super().__init__()
887
+ self.C = config
888
+ D = config.dim
889
+
890
+ c1, c2, c3 = D, D // 2, D // 4
891
+ self.pyramid = FeaturePyramid(config.in_channels, (c1, c2, c3))
892
+
893
+ self.proj_coarse = nn.Sequential(nn.LayerNorm(c1), nn.Linear(c1, D))
894
+ self.proj_medium = nn.Sequential(nn.LayerNorm(c2), nn.Linear(c2, D))
895
+ self.proj_fine = nn.Sequential(nn.LayerNorm(c3), nn.Linear(c3, D))
896
+
897
+ h_c, h_m, h_f = config.img_size // 16, config.img_size // 8, config.img_size // 4
898
+
899
+ def build_coords(h, scale, offset):
900
+ r = torch.arange(h)
901
+ c = torch.arange(h)
902
+ grid_r, grid_c = torch.meshgrid(r, c, indexing='ij')
903
+ coords = torch.stack([grid_r * scale + offset, grid_c * scale + offset], dim=-1).flatten(0, 1)
904
+ return coords.float()
905
+
906
+ self.register_buffer('coords_c', build_coords(h_c, 16, 8))
907
+ self.register_buffer('coords_m', build_coords(h_m, 8, 4))
908
+ self.register_buffer('coords_f', build_coords(h_f, 4, 2))
909
+ self.rope = RoPE2D(D // config.num_heads)
910
+ self.modulate_c2m = nn.Linear(D, 2 * D)
911
+ self.modulate_m2f = nn.Linear(D, 2 * D)
912
+
913
+ self.register_buffer('c2m_idx', self._build_hierarchy_map(h_c, h_c, h_m, h_m))
914
+ self.register_buffer('m2f_idx', self._build_hierarchy_map(h_m, h_m, h_f, h_f))
915
+
916
+ # Pre-compute static coordinate & RoPE grids for all loops (persistent=False preserves checkpoint keys)
917
+ cls_coord = torch.full((1, 1, 2), -1.0)
918
+ coord0_static = torch.cat([cls_coord, self.coords_c.unsqueeze(0)], dim=1)
919
+ sin0_static, cos0_static = self.rope(coord0_static)
920
+ self.register_buffer('sin0_static', sin0_static, persistent=False)
921
+ self.register_buffer('cos0_static', cos0_static, persistent=False)
922
+
923
+ sin_m_static, cos_m_static = self.rope(self.coords_m.unsqueeze(0))
924
+ self.register_buffer('sin_m_static', sin_m_static, persistent=False)
925
+ self.register_buffer('cos_m_static', cos_m_static, persistent=False)
926
+
927
+ sin_f_static, cos_f_static = self.rope(self.coords_f.unsqueeze(0))
928
+ self.register_buffer('sin_f_static', sin_f_static, persistent=False)
929
+ self.register_buffer('cos_f_static', cos_f_static, persistent=False)
930
+
931
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, D))
932
+ self.scale_embed_c = nn.Parameter(torch.zeros(1, 1, D))
933
+ self.scale_embed_m = nn.Parameter(torch.zeros(1, 1, D))
934
+ self.scale_embed_f = nn.Parameter(torch.zeros(1, 1, D))
935
+ self.loop_embed = nn.Embedding(3, D)
936
+ # Pre-cache loop index tensors to avoid re-allocating every forward pass
937
+ self.register_buffer('_loop_ids', torch.arange(3))
938
+
939
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.depth)]
940
+ self.blocks = nn.ModuleList([
941
+ AttentionBlock(D, config.num_heads, config.mlp_ratio, config.dropout, drop_path=dpr[i])
942
+ for i in range(config.depth)
943
+ ])
944
+
945
+ # CLS-to-patch gated broadcast — improves patch representations
946
+ self.cls_gate = nn.Sequential(nn.Linear(D, D), nn.Sigmoid())
947
+
948
+ self.norm = nn.LayerNorm(D, eps=1e-6)
949
+ self.head = nn.Linear(D, config.num_classes)
950
+ self.score_proj = nn.ModuleList([nn.Linear(D, 1) for _ in range(2)])
951
+
952
+ self._init_weights()
953
+
954
+ def _build_hierarchy_map(self, hc, wc, hm, wm):
955
+ # Fully vectorized: compute all parent (r,c) pairs at once
956
+ idx = torch.arange(hc * wc)
957
+ r = (idx // wc).unsqueeze(1) # (N,1)
958
+ c = (idx % wc).unsqueeze(1) # (N,1)
959
+ dr = torch.tensor([0, 0, 1, 1])
960
+ dc = torch.tensor([0, 1, 0, 1])
961
+ return ((2 * r + dr) * wm + (2 * c + dc)).long() # (N,4)
962
+
963
+ def _init_weights(self):
964
+ for m in self.modules():
965
+ if isinstance(m, nn.Linear):
966
+ nn.init.trunc_normal_(m.weight, std=0.02)
967
+ if m.bias is not None: nn.init.zeros_(m.bias)
968
+ elif isinstance(m, nn.Embedding):
969
+ nn.init.trunc_normal_(m.weight, std=0.02)
970
+ nn.init.trunc_normal_(self.cls_token, std=0.02)
971
+ nn.init.trunc_normal_(self.scale_embed_c, std=0.02)
972
+ nn.init.trunc_normal_(self.scale_embed_m, std=0.02)
973
+ nn.init.trunc_normal_(self.scale_embed_f, std=0.02)
974
+
975
+ def _tokenize(self, feat, proj):
976
+ tokens = feat.flatten(2).transpose(1, 2)
977
+ return proj(tokens)
978
+
979
+ def _loop(self, seq, sin, cos, loop_idx):
980
+ B = seq.shape[0]
981
+ c_ids = self._loop_ids[loop_idx].expand(B)
982
+ c = self.loop_embed(c_ids).unsqueeze(1)
983
+ seq = seq + c
984
+ for blk_idx, blk in enumerate(self.blocks):
985
+ if loop_idx == 2 and blk_idx == len(self.blocks) - 1:
986
+ # Last block of Loop 2: CLS-only query & MLP optimization (Optimization 3A)
987
+ return blk(seq, sin, cos, loop_idx, cls_only=True)
988
+ if self.training and getattr(self.C, 'use_grad_checkpointing', False):
989
+ seq = torch.utils.checkpoint.checkpoint(blk, seq, sin, cos, loop_idx, use_reentrant=False)
990
+ else:
991
+ seq = blk(seq, sin, cos, loop_idx)
992
+ # CLS-to-patch gated broadcast
993
+ gate = self.cls_gate(seq[:, 0:1])
994
+ seq = torch.cat([seq[:, 0:1], seq[:, 1:] + gate * seq[:, 0:1]], dim=1)
995
+ return seq
996
+
997
+ def forward_train(self, x, tau=1.0):
998
+ B = x.shape[0]
999
+ D = self.C.dim
1000
+ N_c = (self.C.img_size // 16) ** 2
1001
+ D_head = self.sin0_static.shape[-1]
1002
+
1003
+ f_c, f_m, f_f = self.pyramid(x)
1004
+ t_c = self._tokenize(f_c, self.proj_coarse) + self.scale_embed_c
1005
+ cls = self.cls_token.expand(B, -1, -1)
1006
+
1007
+ sin_cls = self.sin0_static[:, 0:1, :].expand(B, -1, -1)
1008
+ cos_cls = self.cos0_static[:, 0:1, :].expand(B, -1, -1)
1009
+
1010
+ # --- Loop 0 ---
1011
+ seq0 = torch.cat([cls, t_c], 1)
1012
+ sin0 = self.sin0_static.expand(B, -1, -1)
1013
+ cos0 = self.cos0_static.expand(B, -1, -1)
1014
+
1015
+ seq0_out = self._loop(seq0, sin0, cos0, 0)
1016
+ seq0_normed = self.norm(seq0_out)
1017
+ l0 = self.head(seq0_normed[:, 0])
1018
+
1019
+ # Saliency on Coarse
1020
+ cls0_out = seq0_out[:, 0:1, :]
1021
+ tc0_out = seq0_out[:, 1:1 + N_c, :]
1022
+
1023
+ cls0_normed = seq0_normed[:, 0:1, :]
1024
+ tc0_normed = seq0_normed[:, 1:1 + N_c, :]
1025
+
1026
+ saliency_c = torch.clamp(self.score_proj[0](tc0_normed * cls0_normed).squeeze(-1), min=-50.0, max=50.0)
1027
+ mask_c, topk_c, botk_c = differentiable_topk(saliency_c, self.C.K1, tau=tau, training=self.training)
1028
+
1029
+ # Sort selected indices for coalesced GPU memory access
1030
+ topk_c, _ = torch.sort(topk_c, dim=-1)
1031
+
1032
+ selected_m_idx = self.c2m_idx[topk_c].view(B, -1)
1033
+ # Gather-first projection: project only selected medium patches
1034
+ feat_m = f_m.flatten(2).transpose(1, 2)
1035
+ selected_m_raw = feat_m.gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, feat_m.shape[-1]))
1036
+ selected_m_tokens = self.proj_medium(selected_m_raw) + self.scale_embed_m
1037
+
1038
+ # Precomputed RoPE gather for medium patches
1039
+ sin_m_selected = self.sin_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
1040
+ cos_m_selected = self.cos_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
1041
+
1042
+ top_mask_c = mask_c.gather(1, topk_c).unsqueeze(-1)
1043
+ context_c = tc0_out.gather(1, topk_c.unsqueeze(-1).expand(-1, -1, D)) * top_mask_c
1044
+ gb_c = self.modulate_c2m(context_c).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
1045
+ gamma_c, beta_c = gb_c.chunk(2, dim=-1)
1046
+ selected_m_tokens = selected_m_tokens * (1 + gamma_c) + beta_c
1047
+
1048
+ num_retained_c = N_c - self.C.K1
1049
+ if num_retained_c > 0:
1050
+ bot_mask_c = (1.0 - mask_c).gather(1, botk_c).unsqueeze(-1)
1051
+ retained_c_tokens = tc0_out.gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D)) * bot_mask_c
1052
+ sin_c_retained = self.sin0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
1053
+ cos_c_retained = self.cos0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
1054
+ seq1 = torch.cat([cls0_out, retained_c_tokens, selected_m_tokens], dim=1)
1055
+ sin1 = torch.cat([sin_cls, sin_c_retained, sin_m_selected], dim=1)
1056
+ cos1 = torch.cat([cos_cls, cos_c_retained, cos_m_selected], dim=1)
1057
+ else:
1058
+ seq1 = torch.cat([cls0_out, selected_m_tokens], dim=1)
1059
+ sin1 = torch.cat([sin_cls, sin_m_selected], dim=1)
1060
+ cos1 = torch.cat([cos_cls, cos_m_selected], dim=1)
1061
+
1062
+ # --- Loop 1 ---
1063
+ seq1_out = self._loop(seq1, sin1, cos1, 1)
1064
+ seq1_normed = self.norm(seq1_out)
1065
+ l1 = self.head(seq1_normed[:, 0])
1066
+
1067
+ cls1_out = seq1_out[:, 0:1, :]
1068
+ tm1_out = seq1_out[:, 1 + num_retained_c:, :]
1069
+
1070
+ cls1_normed = seq1_normed[:, 0:1, :]
1071
+ tm1_normed = seq1_normed[:, 1 + num_retained_c:, :]
1072
+
1073
+ saliency_m = torch.clamp(self.score_proj[1](tm1_normed * cls1_normed).squeeze(-1), min=-50.0, max=50.0)
1074
+ mask_m, topk_m_local, botk_m = differentiable_topk(saliency_m, self.C.K2, tau=tau, training=self.training)
1075
+
1076
+ # Sort selected local indices for coalesced GPU memory access
1077
+ topk_m_local, _ = torch.sort(topk_m_local, dim=-1)
1078
+
1079
+ global_m_idx = selected_m_idx.gather(1, topk_m_local)
1080
+ selected_f_idx = self.m2f_idx[global_m_idx].view(B, -1)
1081
+
1082
+ # Gather-first projection: project only selected fine patches
1083
+ feat_f = f_f.flatten(2).transpose(1, 2)
1084
+ selected_f_raw = feat_f.gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, feat_f.shape[-1]))
1085
+ selected_f_tokens = self.proj_fine(selected_f_raw) + self.scale_embed_f
1086
+
1087
+ # Precomputed RoPE gather for fine patches
1088
+ sin_f_selected = self.sin_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
1089
+ cos_f_selected = self.cos_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
1090
+
1091
+ top_mask_m = mask_m.gather(1, topk_m_local).unsqueeze(-1)
1092
+ context_m = tm1_out.gather(1, topk_m_local.unsqueeze(-1).expand(-1, -1, D)) * top_mask_m
1093
+ gb_m = self.modulate_m2f(context_m).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
1094
+ gamma_m, beta_m = gb_m.chunk(2, dim=-1)
1095
+ selected_f_tokens = selected_f_tokens * (1 + gamma_m) + beta_m
1096
+
1097
+ num_m = 4 * self.C.K1
1098
+ num_retained_m = num_m - self.C.K2
1099
+ if num_retained_m > 0:
1100
+ bot_mask_m = (1.0 - mask_m).gather(1, botk_m).unsqueeze(-1)
1101
+ retained_m_tokens = tm1_out.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D)) * bot_mask_m
1102
+ sin_m_retained = sin_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
1103
+ cos_m_retained = cos_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
1104
+
1105
+ if num_retained_c > 0:
1106
+ retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
1107
+ seq2 = torch.cat([cls1_out, retained_c_out, retained_m_tokens, selected_f_tokens], dim=1)
1108
+ sin2 = torch.cat([sin_cls, sin_c_retained, sin_m_retained, sin_f_selected], dim=1)
1109
+ cos2 = torch.cat([cos_cls, cos_c_retained, cos_m_retained, cos_f_selected], dim=1)
1110
+ else:
1111
+ seq2 = torch.cat([cls1_out, retained_m_tokens, selected_f_tokens], dim=1)
1112
+ sin2 = torch.cat([sin_cls, sin_m_retained, sin_f_selected], dim=1)
1113
+ cos2 = torch.cat([cos_cls, cos_m_retained, cos_f_selected], dim=1)
1114
+ else:
1115
+ if num_retained_c > 0:
1116
+ retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
1117
+ seq2 = torch.cat([cls1_out, retained_c_out, selected_f_tokens], dim=1)
1118
+ sin2 = torch.cat([sin_cls, sin_c_retained, sin_f_selected], dim=1)
1119
+ cos2 = torch.cat([cos_cls, cos_c_retained, cos_f_selected], dim=1)
1120
+ else:
1121
+ seq2 = torch.cat([cls1_out, selected_f_tokens], dim=1)
1122
+ sin2 = torch.cat([sin_cls, sin_f_selected], dim=1)
1123
+ cos2 = torch.cat([cos_cls, cos_f_selected], dim=1)
1124
+
1125
+ # --- Loop 2 ---
1126
+ seq2_out = self._loop(seq2, sin2, cos2, 2)
1127
+ l2 = self.head(self.norm(seq2_out[:, 0]))
1128
+
1129
+ entropy_loss = -torch.mean(F.softmax(saliency_c, dim=-1) * F.log_softmax(saliency_c, dim=-1))
1130
+ entropy_loss += -torch.mean(F.softmax(saliency_m, dim=-1) * F.log_softmax(saliency_m, dim=-1))
1131
+
1132
+ stats = {
1133
+ 'sal_c_mean': saliency_c.mean(),
1134
+ 'sal_c_std': saliency_c.std(),
1135
+ 'sal_m_mean': saliency_m.mean(),
1136
+ 'sal_m_std': saliency_m.std()
1137
+ }
1138
+
1139
+ return torch.stack([l0, l1, l2]), entropy_loss, stats
1140
+
1141
+ @torch.no_grad()
1142
+ def forward_eval(self, x, exit_conf=0.9, max_loops=None, visualize=False, return_saliency=False):
1143
+ B = x.shape[0]
1144
+ D = self.C.dim
1145
+ N_c = (self.C.img_size // 16) ** 2
1146
+ D_head = self.sin0_static.shape[-1]
1147
+
1148
+ f_c, f_m, f_f = self.pyramid(x)
1149
+ t_c = self._tokenize(f_c, self.proj_coarse) + self.scale_embed_c
1150
+ cls = self.cls_token.expand(B, -1, -1)
1151
+
1152
+ sin_cls = self.sin0_static[:, 0:1, :].expand(B, -1, -1)
1153
+ cos_cls = self.cos0_static[:, 0:1, :].expand(B, -1, -1)
1154
+
1155
+ # L0
1156
+ seq0 = torch.cat([cls, t_c], 1)
1157
+ sin0 = self.sin0_static.expand(B, -1, -1)
1158
+ cos0 = self.cos0_static.expand(B, -1, -1)
1159
+
1160
+ seq0_out = self._loop(seq0, sin0, cos0, 0)
1161
+ seq0_normed = self.norm(seq0_out)
1162
+ l0 = self.head(seq0_normed[:, 0])
1163
+ conf0 = F.softmax(l0, -1).max(-1).values
1164
+ done0 = conf0 >= exit_conf
1165
+
1166
+ if (max_loops == 1 or done0.all()) and not visualize and not return_saliency:
1167
+ return l0, torch.ones(B, device=l0.device), 0.0
1168
+
1169
+ # L1
1170
+ cls0_out = seq0_out[:, 0:1, :]
1171
+ tc0_out = seq0_out[:, 1:1 + N_c, :]
1172
+
1173
+ cls0_normed = seq0_normed[:, 0:1, :]
1174
+ tc0_normed = seq0_normed[:, 1:1 + N_c, :]
1175
+
1176
+ saliency_c = torch.clamp(self.score_proj[0](tc0_normed * cls0_normed).squeeze(-1), min=-50.0, max=50.0)
1177
+ _, topk_c, botk_c = differentiable_topk(saliency_c, self.C.K1, tau=1.0, training=self.training)
1178
+
1179
+ # Sort selected indices for coalesced GPU memory access
1180
+ topk_c, _ = torch.sort(topk_c, dim=-1)
1181
+
1182
+ selected_m_idx = self.c2m_idx[topk_c].view(B, -1)
1183
+ feat_m = f_m.flatten(2).transpose(1, 2)
1184
+ selected_m_raw = feat_m.gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, feat_m.shape[-1]))
1185
+ selected_m_tokens = self.proj_medium(selected_m_raw) + self.scale_embed_m
1186
+
1187
+ # Fast RoPE gather (no dynamic trigonometry)
1188
+ sin_m_selected = self.sin_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
1189
+ cos_m_selected = self.cos_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
1190
+
1191
+ # In inference, mask is mathematically 1.0 (STE bypass)
1192
+ context_c = tc0_out.gather(1, topk_c.unsqueeze(-1).expand(-1, -1, D))
1193
+ gb_c = self.modulate_c2m(context_c).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
1194
+ gamma_c, beta_c = gb_c.chunk(2, dim=-1)
1195
+ selected_m_tokens = selected_m_tokens * (1 + gamma_c) + beta_c
1196
+
1197
+ num_retained_c = N_c - self.C.K1
1198
+ if num_retained_c > 0:
1199
+ retained_c_tokens = tc0_out.gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D))
1200
+ sin_c_retained = self.sin0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
1201
+ cos_c_retained = self.cos0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
1202
+ seq1 = torch.cat([cls0_out, retained_c_tokens, selected_m_tokens], dim=1)
1203
+ sin1 = torch.cat([sin_cls, sin_c_retained, sin_m_selected], dim=1)
1204
+ cos1 = torch.cat([cos_cls, cos_c_retained, cos_m_selected], dim=1)
1205
+ else:
1206
+ seq1 = torch.cat([cls0_out, selected_m_tokens], dim=1)
1207
+ sin1 = torch.cat([sin_cls, sin_m_selected], dim=1)
1208
+ cos1 = torch.cat([cos_cls, cos_m_selected], dim=1)
1209
+
1210
+ seq1_out = self._loop(seq1, sin1, cos1, 1)
1211
+ seq1_normed = self.norm(seq1_out)
1212
+ l1 = self.head(seq1_normed[:, 0])
1213
+ conf1 = F.softmax(l1, -1).max(-1).values
1214
+ done1 = (conf1 >= exit_conf) | done0
1215
+
1216
+ if (max_loops == 2 or done1.all()) and not visualize and not return_saliency:
1217
+ out = torch.where(done0.unsqueeze(-1), l0, l1)
1218
+ loops = 1.0 * done0 + 2.0 * (~done0)
1219
+ return out, loops.float(), 0.0
1220
+
1221
+ # L2
1222
+ cls1_out = seq1_out[:, 0:1, :]
1223
+ tm1_out = seq1_out[:, 1 + num_retained_c:, :]
1224
+
1225
+ cls1_normed = seq1_normed[:, 0:1, :]
1226
+ tm1_normed = seq1_normed[:, 1 + num_retained_c:, :]
1227
+
1228
+ saliency_m = torch.clamp(self.score_proj[1](tm1_normed * cls1_normed).squeeze(-1), min=-50.0, max=50.0)
1229
+ _, topk_m_local, botk_m = differentiable_topk(saliency_m, self.C.K2, tau=1.0, training=self.training)
1230
+
1231
+ # Sort selected local indices for coalesced GPU memory access
1232
+ topk_m_local, _ = torch.sort(topk_m_local, dim=-1)
1233
+
1234
+ global_m_idx = selected_m_idx.gather(1, topk_m_local)
1235
+ selected_f_idx = self.m2f_idx[global_m_idx].view(B, -1)
1236
+
1237
+ feat_f = f_f.flatten(2).transpose(1, 2)
1238
+ selected_f_raw = feat_f.gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, feat_f.shape[-1]))
1239
+ selected_f_tokens = self.proj_fine(selected_f_raw) + self.scale_embed_f
1240
+
1241
+ sin_f_selected = self.sin_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
1242
+ cos_f_selected = self.cos_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
1243
+
1244
+ context_m = tm1_out.gather(1, topk_m_local.unsqueeze(-1).expand(-1, -1, D))
1245
+ gb_m = self.modulate_m2f(context_m).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
1246
+ gamma_m, beta_m = gb_m.chunk(2, dim=-1)
1247
+ selected_f_tokens = selected_f_tokens * (1 + gamma_m) + beta_m
1248
+
1249
+ num_m = 4 * self.C.K1
1250
+ num_retained_m = num_m - self.C.K2
1251
+ if num_retained_m > 0:
1252
+ retained_m_tokens = tm1_out.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D))
1253
+ sin_m_retained = sin_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
1254
+ cos_m_retained = cos_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
1255
+
1256
+ if num_retained_c > 0:
1257
+ retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
1258
+ seq2 = torch.cat([cls1_out, retained_c_out, retained_m_tokens, selected_f_tokens], dim=1)
1259
+ sin2 = torch.cat([sin_cls, sin_c_retained, sin_m_retained, sin_f_selected], dim=1)
1260
+ cos2 = torch.cat([cos_cls, cos_c_retained, cos_m_retained, cos_f_selected], dim=1)
1261
+ else:
1262
+ seq2 = torch.cat([cls1_out, retained_m_tokens, selected_f_tokens], dim=1)
1263
+ sin2 = torch.cat([sin_cls, sin_m_retained, sin_f_selected], dim=1)
1264
+ cos2 = torch.cat([cos_cls, cos_m_retained, cos_f_selected], dim=1)
1265
+ else:
1266
+ if num_retained_c > 0:
1267
+ retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
1268
+ seq2 = torch.cat([cls1_out, retained_c_out, selected_f_tokens], dim=1)
1269
+ sin2 = torch.cat([sin_cls, sin_c_retained, sin_f_selected], dim=1)
1270
+ cos2 = torch.cat([cos_cls, cos_c_retained, cos_f_selected], dim=1)
1271
+ else:
1272
+ seq2 = torch.cat([cls1_out, selected_f_tokens], dim=1)
1273
+ sin2 = torch.cat([sin_cls, sin_f_selected], dim=1)
1274
+ cos2 = torch.cat([cos_cls, cos_f_selected], dim=1)
1275
+
1276
+ seq2_out = self._loop(seq2, sin2, cos2, 2)
1277
+ l2 = self.head(self.norm(seq2_out[:, 0]))
1278
+
1279
+ if visualize:
1280
+ return l2, 3.0, (topk_c[0].cpu().tolist(), global_m_idx[0].cpu().tolist())
1281
+
1282
+ out = torch.where(done0.unsqueeze(-1), l0, torch.where(done1.unsqueeze(-1), l1, l2))
1283
+ loops = 1.0 * done0 + 2.0 * (done1 & ~done0) + 3.0 * (~done1)
1284
+
1285
+ if return_saliency:
1286
+ return out, loops.float(), (topk_c, global_m_idx)
1287
+
1288
+ return out, loops.float(), 0.0
1289
+
1290
+ def forward(self, x, tau=1.0, exit_conf=0.9):
1291
+ if self.training:
1292
+ return self.forward_train(x, tau=tau)
1293
+ with torch.no_grad():
1294
+ return self.forward_eval(x, exit_conf=exit_conf)[0]
1295
+
1296
+
1297
+ # Alias for backward compatibility
1298
+ RemSViT = FoViT
1299
+
1300
+
1301
+ # ==============================================================================
1302
+ # TRAINING
1303
+ # ==============================================================================
1304
+ def get_param_groups(model, lr, weight_decay, lr_decay=0.65):
1305
+ """Layer-wise LR decay: backbone gets lower LR, head gets full LR."""
1306
+ no_decay = {'bias', 'norm', 'LayerNorm', 'BatchNorm'}
1307
+
1308
+ backbone_params = []
1309
+ head_params = []
1310
+
1311
+ for name, param in model.named_parameters():
1312
+ if not param.requires_grad:
1313
+ continue
1314
+ is_backbone = 'pyramid' in name or 'blocks' in name
1315
+ wd = 0.0 if any(nd in name for nd in no_decay) else weight_decay
1316
+
1317
+ if is_backbone:
1318
+ backbone_params.append({'params': param, 'lr': lr * lr_decay, 'weight_decay': wd})
1319
+ else:
1320
+ head_params.append({'params': param, 'lr': lr, 'weight_decay': wd})
1321
+
1322
+ return backbone_params + head_params
1323
+
1324
+
1325
+ def load_matched_state_dict(model: nn.Module, state_or_path, device=None):
1326
+ """
1327
+ Load state dict into model with proper head handling:
1328
+ - Retains and loads checkpoint head if shape matches model.head.
1329
+ - Replaces and re-initializes head ONLY on dimension/shape mismatch or absence.
1330
+ - Robust to legacy prefixes, DDP wrappers, and EMA dictionaries.
1331
+ """
1332
+ if isinstance(state_or_path, str):
1333
+ if not os.path.exists(state_or_path):
1334
+ print(f" [WARN] Checkpoint not found at {state_or_path}. Skipping.")
1335
+ return {}, {}, False
1336
+ state = torch.load(state_or_path, map_location=device or 'cpu')
1337
+ else:
1338
+ state = state_or_path
1339
+
1340
+ # Unwrap checkpoint dictionary prioritizing EMA first
1341
+ if isinstance(state, dict):
1342
+ if 'ema' in state and isinstance(state['ema'], dict) and any(k.endswith('head.weight') for k in state['ema']):
1343
+ state = state['ema']
1344
+ elif 'model' in state and isinstance(state['model'], dict):
1345
+ state = state['model']
1346
+ elif 'state_dict' in state and isinstance(state['state_dict'], dict):
1347
+ state = state['state_dict']
1348
+
1349
+ key_mappings = {
1350
+ "_orig_mod.": "",
1351
+ "module.": "",
1352
+ "film_c2m": "modulate_c2m",
1353
+ "film_m2f": "modulate_m2f",
1354
+ "score_head": "score_proj",
1355
+ "saliency_head": "score_proj",
1356
+ "saliency_proj": "score_proj",
1357
+ "stem_pyramid": "pyramid",
1358
+ "fovea_blocks": "blocks",
1359
+ }
1360
+
1361
+ new_state = {}
1362
+ for k, v in state.items():
1363
+ clean_k = k
1364
+ for old_name, new_name in key_mappings.items():
1365
+ clean_k = clean_k.replace(old_name, new_name)
1366
+ new_state[clean_k] = v
1367
+ state = new_state
1368
+
1369
+ model_state = model.state_dict()
1370
+ matched_state = {}
1371
+ head_mismatch = False
1372
+
1373
+ for k, v in state.items():
1374
+ if k in model_state:
1375
+ if model_state[k].shape == v.shape:
1376
+ matched_state[k] = v
1377
+ else:
1378
+ if k.startswith("head."):
1379
+ head_mismatch = True
1380
+ print(f" [Head Mismatch] Checkpoint '{k}' shape {list(v.shape)} != model shape {list(model_state[k].shape)}. Head will be replaced.")
1381
+ else:
1382
+ print(f" [WARN] Shape mismatch for '{k}': checkpoint {list(v.shape)} vs model {list(model_state[k].shape)}")
1383
+ else:
1384
+ suffix_matches = [mk for mk in model_state if
1385
+ (mk.endswith("." + k) or k.endswith("." + mk)) and not mk.startswith("head.")]
1386
+ if len(suffix_matches) == 1 and model_state[suffix_matches[0]].shape == v.shape:
1387
+ matched_state[suffix_matches[0]] = v
1388
+
1389
+ missing, unexpected = model.load_state_dict(matched_state, strict=False)
1390
+
1391
+ non_head_missing = [k for k in missing if not k.startswith("head.")]
1392
+ if non_head_missing:
1393
+ print(f" [WARN] Missing backbone keys: {non_head_missing}")
1394
+ if unexpected:
1395
+ print(f" [WARN] Unexpected keys in checkpoint: {unexpected}")
1396
+
1397
+ # Head replacement logic: replace ONLY if missing or mismatched
1398
+ has_head_weight = 'head.weight' in matched_state
1399
+ has_head_bias = ('head.bias' in matched_state) or (getattr(model.head, 'bias', None) is None)
1400
+ head_matched = has_head_weight and has_head_bias
1401
+
1402
+ if not head_matched:
1403
+ nn.init.trunc_normal_(model.head.weight, std=0.02)
1404
+ if getattr(model.head, 'bias', None) is not None:
1405
+ nn.init.zeros_(model.head.bias)
1406
+ reason = "shape mismatch" if head_mismatch else "missing in checkpoint"
1407
+ print(f" [Head Replacement] Head re-initialized for {model.head.out_features} classes ({reason}).")
1408
+ else:
1409
+ print(f" [Head Preserved] Kept checkpoint classification head ({model.head.out_features} classes matched).")
1410
+
1411
+ loaded_count = len(matched_state)
1412
+ total_backbone_keys = len([k for k in model_state if not k.startswith("head.")])
1413
+ src_desc = state_or_path if isinstance(state_or_path, str) else "state_dict"
1414
+ print(f" Weights loaded successfully from: {src_desc} ({loaded_count}/{total_backbone_keys} backbone parameters matched)")
1415
+
1416
+ return missing, unexpected, head_matched
1417
+
1418
+
1419
+ def load_pretrained_backbone(model: FoViT, checkpoint_path: str, device):
1420
+ """Backwards-compatible wrapper calling load_matched_state_dict."""
1421
+ return load_matched_state_dict(model, checkpoint_path, device=device)
1422
+
1423
+
1424
+ def train(C: Config, model_state_dict=None, return_dict=None, dataloaders=None, model=None):
1425
+ is_master = True
1426
+
1427
+ # 1. Apply seed before doing anything stochastic (dataloaders, model init)
1428
+ if hasattr(C, 'seed'):
1429
+ set_seed(C.seed)
1430
+
1431
+ device = C.device
1432
+ dtype = torch.bfloat16 if device.type != 'mps' else torch.float32
1433
+
1434
+ def ema_avg_fn(avg_param, param, num_avg):
1435
+ decay = min(C.ema_decay, (1 + num_avg) / (10 + num_avg))
1436
+ return avg_param * decay + param * (1 - decay)
1437
+
1438
+ if dataloaders is not None:
1439
+ train_loader, test_loader, num_train, num_test = dataloaders
1440
+ else:
1441
+ train_loader, test_loader, num_train, num_test = DataFactory.get_dataloaders(C)
1442
+
1443
+ nvml_handle = None
1444
+ if is_master:
1445
+ try:
1446
+ if pynvml is not None:
1447
+ pynvml.nvmlInit()
1448
+ nvml_handle = pynvml.nvmlDeviceGetHandleByIndex(0)
1449
+ except Exception:
1450
+ pass
1451
+
1452
+ if model is not None:
1453
+ raw_model = model.to(device)
1454
+ else:
1455
+ raw_model = FoViT(C).to(device)
1456
+ if getattr(C, 'pretrained_path', None) is not None and model_state_dict is None:
1457
+ load_pretrained_backbone(raw_model, C.pretrained_path, device)
1458
+ # --------------------------------------------
1459
+
1460
+ if model_state_dict is not None:
1461
+ load_matched_state_dict(raw_model, model_state_dict, device=device)
1462
+
1463
+ model = raw_model
1464
+ if hasattr(torch, 'compile'):
1465
+ try:
1466
+ model = torch.compile(raw_model)
1467
+ except Exception:
1468
+ pass
1469
+
1470
+ import inspect
1471
+ ema_kwargs = {'avg_fn': ema_avg_fn, 'use_buffers': False}
1472
+ ema = AveragedModel(raw_model, **ema_kwargs)
1473
+
1474
+ if is_master:
1475
+ print(f"\nFoViT | Dataset: {C.dataset} | Device: {device}")
1476
+ count_parameters(model)
1477
+
1478
+ backbone_scale = getattr(C, 'backbone_lr_scale', 1.0)
1479
+ param_groups = get_param_groups(model, C.max_lr, C.weight_decay, lr_decay=backbone_scale)
1480
+ optimizer = optim.AdamW(param_groups, lr=C.max_lr, weight_decay=C.weight_decay)
1481
+
1482
+ from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
1483
+ warmup_epochs = min(C.warmup_epochs, max(0, C.epochs - 1))
1484
+ if warmup_epochs > 0:
1485
+ warmup_sched = LinearLR(optimizer, start_factor=1e-3, total_iters=warmup_epochs)
1486
+ cosine_sched = CosineAnnealingLR(optimizer, T_max=max(1, C.epochs - warmup_epochs), eta_min=C.lrmin)
1487
+ scheduler = SequentialLR(optimizer, schedulers=[warmup_sched, cosine_sched], milestones=[warmup_epochs])
1488
+ else:
1489
+ scheduler = CosineAnnealingLR(optimizer, T_max=max(1, C.epochs), eta_min=C.lrmin)
1490
+
1491
+ if not os.path.exists(C.log_path):
1492
+ with open(C.log_path, 'w', newline='') as f:
1493
+ csv.writer(f).writerow(['Epoch', 'LR', 'Train_Loss', 'Loss_L0', 'Loss_L1', 'Loss_L2',
1494
+ 'Entropy_Loss', 'Sal_C_Mean', 'Sal_C_Std', 'Sal_M_Mean', 'Sal_M_Std',
1495
+ 'Test_Acc', 'Best_Acc', 'Epoch_Time_s'])
1496
+
1497
+ best_acc = 0.0
1498
+ start_epoch = 1
1499
+
1500
+ loop_drop_start_epoch = C.warmup_epochs
1501
+ if getattr(C, 'resume', False) and os.path.exists(getattr(C, 'checkpoint_path', '')):
1502
+ if is_master:
1503
+ print(f" [Checkpoint] Resuming from {C.checkpoint_path}...")
1504
+ try:
1505
+ ckpt = torch.load(C.checkpoint_path, map_location=device)
1506
+
1507
+ saved = ckpt.get('run_hparams')
1508
+ if saved and (saved['max_lr'] != C.max_lr or saved['warmup_epochs'] != C.warmup_epochs or saved[
1509
+ 'epochs'] != C.epochs):
1510
+ raise RuntimeError(
1511
+ f"Config changed since checkpoint was saved ({saved} -> "
1512
+ f"{{'max_lr': {C.max_lr}, 'warmup_epochs': {C.warmup_epochs}, 'epochs': {C.epochs}}}). "
1513
+ f"Resuming would corrupt the LR schedule. Either revert Config or start a fresh run/checkpoint path."
1514
+ )
1515
+ loop_drop_start_epoch = ckpt.get('run_hparams', {}).get('warmup_epochs', C.warmup_epochs)
1516
+
1517
+ getattr(model, '_orig_mod', model).load_state_dict(ckpt['model'])
1518
+ ema.load_state_dict(ckpt['ema'])
1519
+ optimizer.load_state_dict(ckpt['optimizer'])
1520
+ scheduler.load_state_dict(ckpt['scheduler'])
1521
+ start_epoch = ckpt['epoch'] + 1
1522
+ best_acc = ckpt.get('best_acc', 0.0)
1523
+ if is_master:
1524
+ print(f" [Checkpoint] Resumed at epoch {start_epoch} with best acc {best_acc:.2f}%")
1525
+ except Exception as e:
1526
+ if is_master:
1527
+ print(f" [Checkpoint] Failed to load checkpoint: {e}")
1528
+
1529
+ if C.use_mixup:
1530
+ mixup = v2.MixUp(alpha=0.5, num_classes=C.num_classes)
1531
+ cutmix = v2.CutMix(alpha=0.5, num_classes=C.num_classes)
1532
+
1533
+ def apply_mix(inputs, targets):
1534
+ r = torch.rand(1).item()
1535
+ if r < 0.50:
1536
+ return cutmix(inputs, targets) # CutMix dominant for ViTs
1537
+ elif r < 0.80:
1538
+ return mixup(inputs, targets)
1539
+ return inputs, F.one_hot(targets, C.num_classes).float()
1540
+ else:
1541
+ def apply_mix(inputs, targets):
1542
+ return inputs, F.one_hot(targets, C.num_classes).float()
1543
+
1544
+ # fvcore FLOP / MAC Profiling (1 MAC = 1 FLOP)
1545
+ flops_forward_full = get_fvcore_flops(raw_model, C, device)
1546
+ train_tflops_epoch = (3.0 * flops_forward_full * len(train_loader) * C.batch_size) / 1e12
1547
+ eval_tflops_epoch = (flops_forward_full * len(test_loader) * C.batch_size) / 1e12
1548
+
1549
+ import time as _time
1550
+
1551
+ freeze_epochs = getattr(C, 'freeze_backbone_epochs', 0)
1552
+
1553
+ for epoch in range(start_epoch, C.epochs + 1):
1554
+ epoch_start = _time.time()
1555
+ model.train()
1556
+ total_loss = 0.0
1557
+ total_loss_l0 = 0.0
1558
+ total_loss_l1 = 0.0
1559
+ total_loss_l2 = 0.0
1560
+ total_entropy = 0.0
1561
+ sal_c_mean_sum, sal_c_std_sum = 0.0, 0.0
1562
+ sal_m_mean_sum, sal_m_std_sum = 0.0, 0.0
1563
+
1564
+ # Backbone freeze stage: protect pretrained features from random head gradients
1565
+ if freeze_epochs > 0:
1566
+ _core = getattr(model, '_orig_mod', model)
1567
+ if epoch <= freeze_epochs:
1568
+ for name, p in _core.named_parameters():
1569
+ if 'pyramid' in name or 'blocks' in name:
1570
+ p.requires_grad_(False)
1571
+ elif epoch == freeze_epochs + 1:
1572
+ _core.requires_grad_(True)
1573
+ print(f" [Epoch {epoch}] Backbone unfrozen — all parameters now trainable")
1574
+
1575
+ if epoch == start_epoch and is_master:
1576
+ last_lr = scheduler.get_last_lr()[0] if hasattr(scheduler, 'get_last_lr') else optimizer.param_groups[0][
1577
+ 'lr']
1578
+ print(
1579
+ f" [Sanity Check] Starting/Resuming at Epoch: {epoch} | Scheduler Last Epoch: {scheduler.last_epoch} | Current LR: {last_lr:.2e}")
1580
+
1581
+ # Tau annealing: stay soft during warmup, then linearly harden over next 50 epochs
1582
+ if epoch <= loop_drop_start_epoch:
1583
+ tau_val = 1.0
1584
+ else:
1585
+ tau_val = max(0.1, 1.0 - (epoch - loop_drop_start_epoch) / 50.0)
1586
+ tau = torch.tensor(tau_val, device=device, dtype=dtype)
1587
+
1588
+ start_train_energy = get_energy(nvml_handle)
1589
+ optimizer.zero_grad(set_to_none=True)
1590
+ for batch_idx, (inputs, targets) in enumerate(
1591
+ tqdm(train_loader, desc=f"Epoch {epoch}/{C.epochs} Train", leave=False)):
1592
+ inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
1593
+
1594
+ inputs, targets_mixed = apply_mix(inputs, targets)
1595
+
1596
+ with torch.autocast(device_type=device.type, dtype=dtype):
1597
+ logits_stack, entropy_loss, stats = model(inputs, tau=tau)
1598
+
1599
+ l0, l1, l2 = logits_stack[0], logits_stack[1], logits_stack[2]
1600
+ loss_l2_val = F.cross_entropy(l2, targets_mixed, label_smoothing=C.label_smoothing)
1601
+
1602
+ # Supervision for early exits
1603
+ ce_l1 = F.cross_entropy(l1, targets_mixed, label_smoothing=C.label_smoothing)
1604
+ ce_l0 = F.cross_entropy(l0, targets_mixed, label_smoothing=C.label_smoothing)
1605
+
1606
+ # Self-distillation: L2 teaches L1 and L0 via soft targets
1607
+ T_dist = max(2.0, 4.0 * (1 - epoch / C.epochs))
1608
+ soft_targets = F.softmax(l2.detach() / T_dist, dim=-1)
1609
+ loss_l1_val = ce_l1 + F.kl_div(F.log_softmax(l1 / T_dist, dim=-1), soft_targets,
1610
+ reduction='batchmean') * (T_dist ** 2)
1611
+ loss_l0_val = ce_l0 + F.kl_div(F.log_softmax(l0 / T_dist, dim=-1), soft_targets,
1612
+ reduction='batchmean') * (T_dist ** 2)
1613
+
1614
+ w_l1 = max(0.1, 0.5 * (1 - epoch / C.epochs))
1615
+ w_l0 = max(0.05, 0.3 * (1 - epoch / C.epochs))
1616
+ ent_weight = 0.01
1617
+ loss = loss_l2_val + w_l1 * loss_l1_val + w_l0 * loss_l0_val + ent_weight * entropy_loss
1618
+ loss = loss / getattr(C, 'accum_iter', 1)
1619
+
1620
+ total_loss += (loss * getattr(C, 'accum_iter', 1)).item()
1621
+ total_loss_l0 += loss_l0_val.item()
1622
+ total_loss_l1 += loss_l1_val.item()
1623
+ total_loss_l2 += loss_l2_val.item()
1624
+ total_entropy += entropy_loss.item()
1625
+
1626
+ sal_c_mean_sum += stats.get('sal_c_mean', torch.tensor(0.0, device=device)).item()
1627
+ sal_c_std_sum += stats.get('sal_c_std', torch.tensor(0.0, device=device)).item()
1628
+ sal_m_mean_sum += stats.get('sal_m_mean', torch.tensor(0.0, device=device)).item()
1629
+ sal_m_std_sum += stats.get('sal_m_std', torch.tensor(0.0, device=device)).item()
1630
+
1631
+ loss.backward()
1632
+
1633
+ if ((batch_idx + 1) % getattr(C, 'accum_iter', 1) == 0) or (batch_idx + 1 == len(train_loader)):
1634
+ torch.nn.utils.clip_grad_norm_(model.parameters(), C.grad_clip)
1635
+ optimizer.step()
1636
+ ema.update_parameters(raw_model)
1637
+ optimizer.zero_grad(set_to_none=True)
1638
+
1639
+ # Step scheduler unconditionally once per epoch
1640
+ scheduler.step()
1641
+
1642
+ end_train_energy = get_energy(nvml_handle)
1643
+ train_energy_j = end_train_energy - start_train_energy
1644
+ train_tflops = train_tflops_epoch
1645
+
1646
+ # Eval
1647
+ ema.eval()
1648
+ correct = total = 0
1649
+ start_energy = get_energy(nvml_handle)
1650
+
1651
+ with torch.no_grad(), torch.autocast(device_type=device.type, dtype=dtype):
1652
+ for inputs, targets in tqdm(test_loader, desc=f"Epoch {epoch} Eval", leave=False):
1653
+ inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
1654
+ logits = ema(inputs)
1655
+
1656
+ b_correct = logits.argmax(1).eq(targets).sum()
1657
+ b_total = torch.tensor(targets.size(0), device=device)
1658
+ total += b_total.item()
1659
+ correct += b_correct.item()
1660
+
1661
+ end_energy = get_energy(nvml_handle)
1662
+ energy_j = end_energy - start_energy
1663
+ tflops = eval_tflops_epoch
1664
+
1665
+ acc = 100.0 * (correct.item() if isinstance(correct, torch.Tensor) else correct) / (
1666
+ total.item() if isinstance(total, torch.Tensor) else total)
1667
+ if acc > best_acc:
1668
+ best_acc = acc
1669
+ if is_master:
1670
+ core = getattr(ema.module, '_orig_mod', ema.module)
1671
+ torch.save(core.state_dict(), C.save_path)
1672
+
1673
+ n_batches = len(train_loader)
1674
+ avg_loss = total_loss.item() / n_batches if isinstance(total_loss, torch.Tensor) else total_loss / n_batches
1675
+ avg_l0 = total_loss_l0.item() / n_batches if isinstance(total_loss_l0,
1676
+ torch.Tensor) else total_loss_l0 / n_batches
1677
+ avg_l1 = total_loss_l1.item() / n_batches if isinstance(total_loss_l1,
1678
+ torch.Tensor) else total_loss_l1 / n_batches
1679
+ avg_l2 = total_loss_l2.item() / n_batches if isinstance(total_loss_l2,
1680
+ torch.Tensor) else total_loss_l2 / n_batches
1681
+ avg_ent = total_entropy.item() / n_batches if isinstance(total_entropy,
1682
+ torch.Tensor) else total_entropy / n_batches
1683
+
1684
+ avg_sc_mean = sal_c_mean_sum.item() / n_batches if isinstance(sal_c_mean_sum,
1685
+ torch.Tensor) else sal_c_mean_sum / n_batches
1686
+ avg_sc_std = sal_c_std_sum.item() / n_batches if isinstance(sal_c_std_sum,
1687
+ torch.Tensor) else sal_c_std_sum / n_batches
1688
+ avg_sm_mean = sal_m_mean_sum.item() / n_batches if isinstance(sal_m_mean_sum,
1689
+ torch.Tensor) else sal_m_mean_sum / n_batches
1690
+ avg_sm_std = sal_m_std_sum.item() / n_batches if isinstance(sal_m_std_sum,
1691
+ torch.Tensor) else sal_m_std_sum / n_batches
1692
+
1693
+ lr = optimizer.param_groups[0]['lr']
1694
+ epoch_time = _time.time() - epoch_start
1695
+
1696
+ if is_master:
1697
+ with open(C.log_path, 'a', newline='') as f:
1698
+ csv.writer(f).writerow([epoch, f'{lr:.2e}', f'{avg_loss:.4f}', f'{avg_l0:.4f}',
1699
+ f'{avg_l1:.4f}', f'{avg_l2:.4f}', f'{avg_ent:.4f}',
1700
+ f'{avg_sc_mean:.4f}', f'{avg_sc_std:.4f}', f'{avg_sm_mean:.4f}',
1701
+ f'{avg_sm_std:.4f}',
1702
+ f'{acc:.2f}', f'{best_acc:.2f}', f'{epoch_time:.1f}'])
1703
+
1704
+ if epoch % 5 == 0 or epoch <= 5:
1705
+ print(
1706
+ f"Epoch {epoch:03d}/{C.epochs} | Loss {avg_loss:.4f} (L2:{avg_l2:.3f} L1:{avg_l1:.3f} L0:{avg_l0:.3f}) | Acc {acc:.2f}% | Best {best_acc:.2f}% | {epoch_time:.1f}s | Train (Energy {train_energy_j:.2f}J, TFLOPs {train_tflops:.4f}) | Eval (Energy {energy_j:.2f}J, TFLOPs {tflops:.4f})")
1707
+ generate_live_plots(C.log_path)
1708
+
1709
+ try:
1710
+ inputs_vis = inputs[0:1]
1711
+ _, _, (tk_c, tk_m) = ema.module.forward_eval(inputs_vis, visualize=True)
1712
+ plot_patch_selection(inputs_vis[0], tk_c, tk_m, epoch, C)
1713
+ except Exception as e:
1714
+ pass
1715
+
1716
+ # Save epoch checkpoint
1717
+ if hasattr(C, 'checkpoint_path'):
1718
+ torch.save({
1719
+ 'epoch': epoch,
1720
+ 'model': getattr(model, '_orig_mod', model).state_dict(),
1721
+ 'ema': ema.state_dict(),
1722
+ 'optimizer': optimizer.state_dict(),
1723
+ 'scheduler': scheduler.state_dict(),
1724
+ 'best_acc': best_acc,
1725
+ 'run_hparams': {'max_lr': C.max_lr, 'warmup_epochs': C.warmup_epochs, 'epochs': C.epochs},
1726
+ }, C.checkpoint_path)
1727
+
1728
+ if is_master:
1729
+ print("\n Training Complete. Final Best Acc:", best_acc)
1730
+
1731
+ if os.path.exists(C.save_path):
1732
+ final = FoViT(C).to(device)
1733
+ load_matched_state_dict(final, C.save_path, device=device)
1734
+ else:
1735
+ final = getattr(ema.module, '_orig_mod', ema.module)
1736
+
1737
+ best_sweep_acc, sweep_dict, sweep_results = evaluate_confidence_sweep(
1738
+ final, test_loader, C, nvml_handle=nvml_handle, is_master=is_master
1739
+ )
1740
+
1741
+ if return_dict is not None and is_master:
1742
+ return_dict['best_sweep_acc'] = best_sweep_acc
1743
+ return_dict['sweep_dict'] = sweep_dict
1744
+
1745
+ return best_sweep_acc, sweep_dict, sweep_results
1746
+
1747
+
1748
+ def evaluate_confidence_sweep(model, test_loader, config, thresholds=None, nvml_handle=None, is_master=True):
1749
+ """
1750
+ Evaluates FoViT model across multiple adaptive early-exit confidence thresholds.
1751
+ Returns (best_sweep_acc, sweep_results_dict, sweep_results_list)
1752
+ """
1753
+ if thresholds is None:
1754
+ thresholds = [0.50, 0.60, 0.70, 0.80, 0.85, 0.90, 0.95, 0.98, 0.99, 1.00]
1755
+
1756
+ device = config.device
1757
+ dtype = torch.bfloat16 if device.type != 'mps' else torch.float32
1758
+
1759
+ if is_master:
1760
+ print("\n" + "=" * 65)
1761
+ print(" FoViT Adaptive Inference: Confidence Score Sweep")
1762
+ print("=" * 65)
1763
+ print(f" {'Threshold':>10} {'Accuracy':>10} {'Avg Loops':>12} {'Energy (J)':>10} {'TFLOPs':>10}")
1764
+
1765
+ best_sweep_acc = 0.0
1766
+ sweep_dict = {}
1767
+ sweep_results = []
1768
+
1769
+ heatmap_c = np.zeros(config.img_size // 16 * config.img_size // 16)
1770
+ heatmap_m = np.zeros(config.img_size // 8 * config.img_size // 8)
1771
+
1772
+ model.eval()
1773
+ with torch.no_grad():
1774
+ for thresh in thresholds:
1775
+ correct = 0
1776
+ total = 0
1777
+ sum_loops = 0.0
1778
+ total_flops = 0.0
1779
+ start_energy = get_energy(nvml_handle)
1780
+
1781
+ exit_counts = {1: 0, 2: 0, 3: 0}
1782
+
1783
+ with torch.autocast(device_type=device.type, dtype=dtype):
1784
+ for inputs, targets in tqdm(test_loader, desc=f"Sweep T={thresh:.2f}", leave=False):
1785
+ inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
1786
+ logits, loops_batch, b_flops = model.forward_eval(inputs, exit_conf=thresh)
1787
+
1788
+ b_correct = logits.argmax(1).eq(targets).sum()
1789
+ b_total = torch.tensor(targets.size(0), device=device)
1790
+
1791
+ if isinstance(loops_batch, torch.Tensor):
1792
+ b_sum_loops = loops_batch.sum()
1793
+ exit_counts[1] += (loops_batch == 1.0).sum().item()
1794
+ exit_counts[2] += (loops_batch == 2.0).sum().item()
1795
+ exit_counts[3] += (loops_batch == 3.0).sum().item()
1796
+ else:
1797
+ b_sum_loops = torch.tensor(loops_batch * targets.size(0), device=device)
1798
+ exit_counts[3] += targets.size(0)
1799
+
1800
+ b_flops_tensor = torch.tensor(b_flops, device=device)
1801
+ total += b_total
1802
+ correct += b_correct
1803
+ sum_loops += b_sum_loops
1804
+ total_flops += b_flops_tensor
1805
+
1806
+ if thresh >= 0.99:
1807
+ try:
1808
+ _, _, (tk_c, tk_m) = model.forward_eval(inputs[0:1], exit_conf=1.0, visualize=True)
1809
+ for idx in tk_c: heatmap_c[idx] += 1
1810
+ for idx in tk_m: heatmap_m[idx] += 1
1811
+ except Exception:
1812
+ pass
1813
+
1814
+ end_energy = get_energy(nvml_handle)
1815
+ energy_j = end_energy - start_energy
1816
+
1817
+ tflops = (total_flops.item() if isinstance(total_flops, torch.Tensor) else total_flops) / 1e12
1818
+
1819
+ tot_val = total.item() if isinstance(total, torch.Tensor) else total
1820
+ corr_val = correct.item() if isinstance(correct, torch.Tensor) else correct
1821
+ sum_loops_val = sum_loops.item() if isinstance(sum_loops, torch.Tensor) else sum_loops
1822
+
1823
+ acc = 100. * corr_val / tot_val if tot_val > 0 else 0
1824
+ avg_loops = sum_loops_val / tot_val if tot_val > 0 else 3.0
1825
+ sweep_dict[thresh] = acc
1826
+
1827
+ if acc > best_sweep_acc:
1828
+ best_sweep_acc = acc
1829
+
1830
+ if is_master:
1831
+ print(f" {thresh:>10.2f} {acc:>9.2f}% {avg_loops:>11.2f} {energy_j:>10.2f} {tflops:>10.4f}")
1832
+ sweep_results.append({
1833
+ 'threshold': thresh, 'accuracy': acc, 'avg_loops': avg_loops,
1834
+ 'tflops': tflops, 'exits': exit_counts
1835
+ })
1836
+
1837
+ if is_master:
1838
+ try:
1839
+ plot_adaptive_inference_sweep(sweep_results)
1840
+ plot_spatial_bias_heatmap(heatmap_c, heatmap_m, config)
1841
+ except Exception:
1842
+ pass
1843
+
1844
+ return best_sweep_acc, sweep_dict, sweep_results
1845
+
1846
+
1847
+ def plot_adaptive_inference_sweep(sweep_results):
1848
+ import matplotlib.pyplot as plt
1849
+ import numpy as np
1850
+
1851
+ plt.rcParams.update({
1852
+ 'figure.facecolor': 'white',
1853
+ 'axes.facecolor': 'white',
1854
+ 'axes.edgecolor': '#333333',
1855
+ 'axes.linewidth': 2.0,
1856
+ 'text.color': '#212529',
1857
+ 'axes.labelcolor': '#212529',
1858
+ 'figure.dpi': 300,
1859
+ 'font.family': 'sans-serif',
1860
+ 'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
1861
+ })
1862
+
1863
+ # 1. Pareto Curve (Accuracy vs TFLOPs)
1864
+ plt.figure(figsize=(10, 6))
1865
+ tflops = [r['tflops'] for r in sweep_results]
1866
+ accs = [r['accuracy'] for r in sweep_results]
1867
+ labels = [f"T>{r['threshold']:.2f}" for r in sweep_results]
1868
+
1869
+ plt.plot(tflops, accs, marker='o', markersize=10, linewidth=2.5, color='#2CA02C', mfc='#FF7F0E')
1870
+ for i, label in enumerate(labels):
1871
+ plt.annotate(label, (tflops[i], accs[i]), textcoords="offset points", xytext=(0, 10), ha='center', fontsize=10,
1872
+ fontweight='bold')
1873
+
1874
+ plt.xlabel('Compute Cost (TFLOPs)', fontweight='bold')
1875
+ plt.ylabel('Evaluation Accuracy (%)', fontweight='bold')
1876
+ plt.grid(True, linestyle='--', alpha=0.7)
1877
+ plt.tight_layout()
1878
+ plt.savefig("adaptive_inference_pareto.pdf", bbox_inches='tight', facecolor='white')
1879
+ plt.close()
1880
+
1881
+ # 2. Exit Distribution Histogram
1882
+ plt.figure(figsize=(10, 6))
1883
+ x = np.arange(len(sweep_results))
1884
+ l1 = np.array([r['exits'][1] for r in sweep_results])
1885
+ l2 = np.array([r['exits'][2] for r in sweep_results])
1886
+ l3 = np.array([r['exits'][3] for r in sweep_results])
1887
+ total = l1 + l2 + l3
1888
+ total[total == 0] = 1 # prevent div zero
1889
+
1890
+ p1 = l1 / total * 100
1891
+ p2 = l2 / total * 100
1892
+ p3 = l3 / total * 100
1893
+
1894
+ width = 0.6
1895
+ plt.bar(x, p1, width, label='Loop 0 (Coarse)', color='#ff6b6b', alpha=0.9)
1896
+ plt.bar(x, p2, width, bottom=p1, label='Loop 1 (Medium)', color='#4dabf7', alpha=0.9)
1897
+ plt.bar(x, p3, width, bottom=p1 + p2, label='Loop 2 (Fine)', color='#51cf66', alpha=0.9)
1898
+
1899
+ plt.xticks(x, [f"T={r['threshold']:.2f}" for r in sweep_results], fontweight='bold')
1900
+ plt.ylabel('Exit Percentage (%)', fontweight='bold')
1901
+ plt.legend(loc='upper right', frameon=True, facecolor='white')
1902
+ plt.tight_layout()
1903
+ plt.savefig("exit_distribution.pdf", bbox_inches='tight', facecolor='white')
1904
+ plt.close()
1905
+
1906
+
1907
+ def plot_spatial_bias_heatmap(heatmap_c, heatmap_m, config):
1908
+ import matplotlib.pyplot as plt
1909
+ import seaborn as sns
1910
+
1911
+ plt.rcParams.update({
1912
+ 'figure.facecolor': 'white',
1913
+ 'axes.facecolor': 'white',
1914
+ 'axes.edgecolor': '#333333',
1915
+ 'axes.linewidth': 2.0,
1916
+ 'text.color': '#212529',
1917
+ 'axes.labelcolor': '#212529',
1918
+ 'figure.dpi': 300,
1919
+ 'font.family': 'sans-serif',
1920
+ 'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
1921
+ })
1922
+
1923
+ grid_w_c = config.img_size // 16
1924
+ grid_w_m = config.img_size // 8
1925
+
1926
+ hm_c = heatmap_c.reshape(grid_w_c, grid_w_c)
1927
+ hm_m = heatmap_m.reshape(grid_w_m, grid_w_m)
1928
+
1929
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor='white')
1930
+
1931
+ sns.heatmap(hm_c, cmap='Reds', ax=axes[0], cbar_kws={'label': 'Selection Frequency'})
1932
+ axes[0].set_xlabel('Spatial X', fontweight='bold')
1933
+ axes[0].set_ylabel('Spatial Y', fontweight='bold')
1934
+
1935
+ sns.heatmap(hm_m, cmap='Blues', ax=axes[1], cbar_kws={'label': 'Selection Frequency'})
1936
+ axes[1].set_xlabel('Spatial X', fontweight='bold')
1937
+ axes[1].set_ylabel('Spatial Y', fontweight='bold')
1938
+
1939
+ plt.tight_layout()
1940
+ plt.savefig("spatial_bias_heatmap.pdf", bbox_inches='tight', facecolor='white')
1941
+ plt.close()
1942
+
1943
+
1944
+ def plot_patch_selection(img_tensor, topk_c, topk_m, epoch, config):
1945
+ import numpy as np
1946
+ import matplotlib.patches as patches
1947
+ from matplotlib.lines import Line2D
1948
+ try:
1949
+ ds = config.dataset.lower()
1950
+ # Use ImageNet stats for VTAB or unknown datasets (matches training normalization)
1951
+ if ds.startswith('vtab') or ds not in DataFactory.STATS:
1952
+ mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1).to(img_tensor.device)
1953
+ std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1).to(img_tensor.device)
1954
+ else:
1955
+ stats = DataFactory.STATS[ds]
1956
+ mean = torch.tensor(stats[0]).view(3, 1, 1).to(img_tensor.device)
1957
+ std = torch.tensor(stats[1]).view(3, 1, 1).to(img_tensor.device)
1958
+
1959
+ img = img_tensor * std + mean
1960
+ img = img.clamp(0, 1).cpu().permute(1, 2, 0).numpy()
1961
+
1962
+ H, W = config.img_size, config.img_size
1963
+
1964
+ plt.rcParams.update({
1965
+ 'figure.facecolor': 'white',
1966
+ 'axes.facecolor': 'white',
1967
+ 'axes.edgecolor': '#333333',
1968
+ 'axes.linewidth': 2.0,
1969
+ 'text.color': '#212529',
1970
+ 'axes.labelcolor': '#212529',
1971
+ 'figure.dpi': 300,
1972
+ 'font.family': 'sans-serif',
1973
+ 'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
1974
+ })
1975
+
1976
+ fig, ax = plt.subplots(1, 1, figsize=(10, 10), facecolor='white')
1977
+ ax.imshow(img)
1978
+ ax.axis('off')
1979
+
1980
+ grid_w = W // 16
1981
+ patch_dim_c = 16
1982
+
1983
+ # Color codes
1984
+ color_c = np.array([1.0, 0.2, 0.2]) # Red for coarse->medium
1985
+ color_m = np.array([0.2, 0.5, 1.0]) # Blue for medium->fine
1986
+
1987
+ # Create alpha blended overlay
1988
+ overlay = np.zeros_like(img, dtype=np.float32)
1989
+ alpha_mask = np.zeros((H, W), dtype=np.float32)
1990
+
1991
+ for idx in topk_c:
1992
+ r, c = idx // grid_w, idx % grid_w
1993
+ y, x = r * patch_dim_c, c * patch_dim_c
1994
+ overlay[y:y + patch_dim_c, x:x + patch_dim_c] = color_c
1995
+ alpha_mask[y:y + patch_dim_c, x:x + patch_dim_c] = 0.35
1996
+
1997
+ rect = patches.Rectangle((x, y), patch_dim_c, patch_dim_c, linewidth=1.5, edgecolor='#ff3333',
1998
+ facecolor='none', alpha=0.8)
1999
+ ax.add_patch(rect)
2000
+
2001
+ grid_mw = W // 8
2002
+ patch_dim_m = 8
2003
+ for idx in topk_m:
2004
+ r, c = idx // grid_mw, idx % grid_mw
2005
+ y, x = r * patch_dim_m, c * patch_dim_m
2006
+ overlay[y:y + patch_dim_m, x:x + patch_dim_m] = color_m
2007
+ alpha_mask[y:y + patch_dim_m, x:x + patch_dim_m] = 0.45
2008
+
2009
+ rect = patches.Rectangle((x, y), patch_dim_m, patch_dim_m, linewidth=1.5, edgecolor='#3366ff',
2010
+ facecolor='none', alpha=0.9)
2011
+ ax.add_patch(rect)
2012
+
2013
+ alpha_mask = np.expand_dims(alpha_mask, axis=-1)
2014
+ blended = img * (1 - alpha_mask) + overlay * alpha_mask
2015
+ ax.imshow(blended)
2016
+
2017
+ legend_elements = [
2018
+ Line2D([0], [0], marker='s', color='w', label='Coarse to Medium',
2019
+ markerfacecolor='#ff3333', markersize=15, alpha=0.7, markeredgewidth=2, markeredgecolor='#ff3333'),
2020
+ Line2D([0], [0], marker='s', color='w', label='Medium to Fine',
2021
+ markerfacecolor='#3366ff', markersize=15, alpha=0.8, markeredgewidth=2, markeredgecolor='#3366ff')
2022
+ ]
2023
+
2024
+ ax.legend(handles=legend_elements, loc='upper right', frameon=True, facecolor='white', framealpha=0.95,
2025
+ fontsize=16, edgecolor='#333333', borderpad=0.8)
2026
+
2027
+ plt.tight_layout()
2028
+ plt.savefig(f"patch_selection_epoch_{epoch:03d}.pdf", bbox_inches='tight', dpi=300, facecolor='white',
2029
+ edgecolor='none')
2030
+ plt.close(fig)
2031
+ except Exception as e:
2032
+ print("Plotting error:", e)
2033
+
2034
+
2035
+ if __name__ == '__main__':
2036
+ cfg = Config()
2037
+ train(cfg)