Download fovit.py from deeplumiere/fovit: direct link, hf CLI and curl.
- Browser
- Download file 90.7 kB
-
https://huggingface.co/deeplumiere/fovit/resolve/main/fovit.py
- Command line
-
hf download hf://deeplumiere/fovit/fovit.py
-
curl -L -o fovit.py https://huggingface.co/deeplumiere/fovit/resolve/main/fovit.py
90.7 kB
# %%writefile remsvit.py
##WORKING MODEL##
import math
import os
import csv
import pickle
from datetime import datetime
from functools import lru_cache
import shutil
import numpy as np
from tqdm import tqdm
try:
import pynvml
except ImportError:
pynvml = None
def _get_writable_cache_dir():
"""Returns a writable directory for caching: /kaggle/working on Kaggle, else cwd."""
kaggle_working = '/kaggle/working'
if os.path.isdir(kaggle_working) and os.access(kaggle_working, os.W_OK):
return kaggle_working
return os.getcwd()
import torch
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
if hasattr(torch, 'set_float32_matmul_precision'):
torch.set_float32_matmul_precision('high')
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.optim.swa_utils import AveragedModel
from torchvision.transforms import v2
import torchvision
import torchvision.transforms as transforms
import os
import shutil
import urllib.request
import subprocess
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import random
def set_seed(seed: int = 42):
"""Make runs deterministic for reproducibility (CVPR requirement)."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Note: deterministic=True and benchmark=False can slow down training.
# We leave benchmark=True here by default as ImageNet needs speed,
# but the seeds alone eliminate 99% of the variance from stochastic ops.
os.environ['PYTHONHASHSEED'] = str(seed)
class Config:
seed = 1992 # For reproducible runs
# Dataset
# For imagenet1k/imagenet100: set data_dir to the PARENT folder that contains
# imagenet_part_1/, imagenet_part_2/, ... OR a single folder with train/ and val/ sub-dirs.
# Example: data_dir = '/kaggle/input/imagenet-object-localization-challenge'
data_dir = "/home/admin/PycharmProjects/Deepresearch/data/archive"
dataset = 'imagenet1k'
num_classes = 1000 # cifar10=10, cifar100=100, imagenet1k=1000, imagenet100=100, tiny_imagenet=200
img_size = 224 # use 224 for imagenet1k/imagenet100
in_channels = 3
num_workers = 16 # WARNING: ImageNet-1K requires AT LEAST 16 workers, otherwise JPEG decoding caps out at ~120 img/s
prefetch_factor = 2
# Architecture
dim = 320
num_heads = 4 # 8 heads × 40 head_dim
depth = 4 # Shared blocks × 3 loops = 12 effective layers
mlp_ratio = 3.0
dropout = 0.1 # Increased for larger capacity
lrmin = 1e-5
# Recurrent Saliency (Pareto-optimal inference defaults)
k1_ratio = 0.35 # % of coarse patches to refine into medium
k2_ratio = 0.45 # % of medium patches to refine into fine
# Training
batch_size = 16 # Reduced from 128 to prevent VRAM swapping
accum_iter = 2 # Gradient accumulation steps
epochs = 50
accelerator = 'gpu' # Options: 'gpu' or 'tpu'
max_lr = 1e-4 # Scaled for smaller batch size
weight_decay = 0.1 # Reduced from 0.2: 0.05 is standard for tiny/small ViTs on ImageNet
label_smoothing = 0.1
ema_decay = 0.9999
grad_clip = 1.0
warmup_epochs = 5 # Short warmup, then cosine decay
drop_path_rate = 0.1 # Reduced from 0.2: small capacity ViTs underfit with high drop_path
use_mixup = True # MixUp/CutMix augmentation (disable for small datasets like VTAB-1k)
backbone_lr_scale = 1.0 # LR multiplier for backbone vs head (lower preserves pretrained features)
freeze_backbone_epochs = 0 # Freeze backbone for N epochs at start (for fine-tuning from pretrained)
save_path = 'eval_outputs/fovit224.pth'
pretrained_path = "eval_outputs/fovit224.pth"
checkpoint_path = 'fovit224_checkpoint_in1k_256.pth'
log_path = 'fovit224_log_in1k_256c10.csv'
resume = True
use_grad_checkpointing = False # Set to True if OOM
device = torch.device(
'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
def __init__(self):
# Auto-configure based on dataset to prevent dimension mismatches
ds = self.dataset.lower()
# if ds == 'imagenet1k':
# self.num_classes = 1000
# if self.img_size == 64: self.img_size = 224
# elif ds == 'imagenet100':
# self.num_classes = 100
# if self.img_size == 64: self.img_size = 224
# elif ds == 'tiny_imagenet':
# self.num_classes = 200
# elif ds == 'cifar10':
# self.num_classes = 10
# elif ds.startswith('vtab_'):
# # num_classes will be set dynamically by DataFactory
# if self.img_size == 64: self.img_size = 128
# Convert percentages to absolute patch counts based on image resolution
# N_c = (self.img_size // 16) ** 2
# self.K1 = max(1, int(N_c * self.k1_ratio))
# self.K2 = max(1, int((self.K1 * 4) * self.k2_ratio))
@property
def K1(self):
N_c = (self.img_size // 16) ** 2
return max(1, int(N_c * self.k1_ratio))
@property
def K2(self):
return max(1, int((self.K1 * 4) * self.k2_ratio))
def count_parameters(model: nn.Module) -> int:
n = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f" Trainable parameters: {n:,}")
return n
def get_energy(handle):
if handle is None or pynvml is None: return 0.0
try:
return pynvml.nvmlDeviceGetTotalEnergyConsumption(handle) / 1000.0
except Exception:
return 0.0
def generate_live_plots(csv_path, save_prefix="fovit_metrics"):
try:
df = pd.read_csv(csv_path)
if len(df) < 2: return
# High quality lab style
sns.set_theme(style="whitegrid", context="talk", font_scale=1.2)
plt.rcParams.update({
"figure.dpi": 300,
"figure.facecolor": "white",
"savefig.facecolor": "white",
"axes.facecolor": "white",
"axes.linewidth": 2.0,
"axes.edgecolor": "#333333",
"grid.color": "#e0e0e0",
"grid.linestyle": "--",
"grid.alpha": 0.7,
"axes.labelsize": 14,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
})
# Plot 1: Train Loss (Separate PDF)
plt.figure(figsize=(10, 6))
ax1 = sns.lineplot(data=df, x='Epoch', y='Train_Loss', color='#D62728', linewidth=2.5, marker='o', markersize=4,
markeredgecolor='white')
ax1.set_xlabel('Training Epoch', fontweight='bold')
ax1.set_ylabel('Cross-Entropy Loss', fontweight='bold')
ax1.fill_between(df['Epoch'], df['Train_Loss'], alpha=0.1, color='#D62728')
plt.tight_layout()
plt.savefig(f"{save_prefix}_loss.pdf", bbox_inches='tight', facecolor='white')
plt.close()
# Plot 2: Accuracy (Separate PDF)
plt.figure(figsize=(10, 6))
ax2 = sns.lineplot(data=df, x='Epoch', y='Test_Acc', color='#1F77B4', label='Eval Top-1 Accuracy', linewidth=2,
alpha=0.7)
sns.lineplot(data=df, x='Epoch', y='Best_Acc', ax=ax2, color='#FF7F0E', label='Best Top-1 Accuracy',
linewidth=2.5, linestyle='--')
ax2.set_xlabel('Training Epoch', fontweight='bold')
ax2.set_ylabel('Accuracy (%)', fontweight='bold')
ax2.legend(loc='lower right', frameon=True, fancybox=True, shadow=True, borderpad=1)
plt.tight_layout()
plt.savefig(f"{save_prefix}_accuracy.pdf", bbox_inches='tight', facecolor='white')
plt.close()
# Plot 3: Learning Rate (Separate PDF)
plt.figure(figsize=(10, 6))
ax3 = sns.lineplot(data=df, x='Epoch', y='LR', color='#2CA02C', linewidth=2.5)
ax3.set_xlabel('Training Epoch', fontweight='bold')
ax3.set_ylabel('Learning Rate', fontweight='bold')
ax3.set_yscale('log')
ax3.fill_between(df['Epoch'], df['LR'], alpha=0.1, color='#2CA02C')
plt.tight_layout()
plt.savefig(f"{save_prefix}_lr.pdf", bbox_inches='tight', facecolor='white')
plt.close()
# Plot 4: Recurrence Losses (Separate PDF)
if 'Loss_L0' in df.columns:
plt.figure(figsize=(10, 6))
ax4 = sns.lineplot(data=df, x='Epoch', y='Loss_L0', color='#1F77B4', label='Loop 0 (Coarse)', linewidth=2.5)
if 'Loss_L1' in df.columns:
sns.lineplot(data=df, x='Epoch', y='Loss_L1', ax=ax4, color='#FF7F0E', label='Loop 1 (Medium)',
linewidth=2.5)
if 'Loss_L2' in df.columns:
sns.lineplot(data=df, x='Epoch', y='Loss_L2', ax=ax4, color='#2CA02C', label='Loop 2 (Fine)',
linewidth=2.5)
ax4.set_xlabel('Training Epoch', fontweight='bold')
ax4.set_ylabel('Cross-Entropy Loss', fontweight='bold')
ax4.legend(loc='upper right', frameon=True, fancybox=True, shadow=True, borderpad=1)
plt.tight_layout()
plt.savefig(f"{save_prefix}_recurrence.pdf", bbox_inches='tight', facecolor='white')
plt.close()
# Plot 5: Entropy Loss (Separate PDF)
if 'Entropy_Loss' in df.columns:
plt.figure(figsize=(10, 6))
ax5 = sns.lineplot(data=df, x='Epoch', y='Entropy_Loss', color='#9467bd', linewidth=2.5)
ax5.set_xlabel('Training Epoch', fontweight='bold')
ax5.set_ylabel('Saliency Entropy', fontweight='bold')
ax5.fill_between(df['Epoch'], df['Entropy_Loss'], alpha=0.1, color='#9467bd')
plt.tight_layout()
plt.savefig(f"{save_prefix}_entropy.pdf", bbox_inches='tight', facecolor='white')
plt.close()
except Exception as e:
print(f"Failed to generate plots: {e}")
# ==============================================================================
# DATA FACTORY
# ==============================================================================
try:
import cv2
_HAS_CV2 = True
except ImportError:
_HAS_CV2 = False
from PIL import Image
def _fast_loader(path):
"""OpenCV-accelerated image loader with PIL fallback."""
if _HAS_CV2:
img = cv2.imread(path)
if img is not None:
return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.open(path).convert('RGB')
class FastImageFolder(torch.utils.data.Dataset):
"""
High-performance ImageNet loader:
- Scans multiple root directories with unified class index.
- Caches the sample manifest (path, target) to disk on first run.
- Uses OpenCV for fast JPEG decoding with PIL fallback.
"""
VALID_EXTS = {'.png', '.jpg', '.jpeg', '.JPEG', '.webp'}
def __init__(self, root_list, transform=None, cache_path=None):
if isinstance(root_list, str):
root_list = [root_list]
root_list = [r for r in root_list if os.path.isdir(r)]
if not root_list:
raise ValueError(f"No valid directories found in: {root_list}")
self.transform = transform
if cache_path is None:
# Always write cache to a writable dir (Kaggle input is read-only)
cache_dir = _get_writable_cache_dir()
cache_key = os.path.basename(os.path.dirname(root_list[0]))
cache_path = os.path.join(cache_dir, f'.fif_cache_{cache_key}.pkl')
if os.path.exists(cache_path):
with open(cache_path, 'rb') as f:
cached = pickle.load(f)
self.classes = cached['classes']
self.class_to_idx = cached['class_to_idx']
self.samples = cached['samples']
print(f"[FastImageFolder] Loaded {len(self.samples):,} samples from cache.")
else:
print(f"[FastImageFolder] Building sample manifest (first run only)...")
self.classes, self.class_to_idx = self._find_classes(root_list)
self.samples = self._make_dataset(root_list)
try:
with open(cache_path, 'wb') as f:
pickle.dump({'classes': self.classes, 'class_to_idx': self.class_to_idx, 'samples': self.samples},
f, protocol=4)
print(f"[FastImageFolder] Cached {len(self.samples):,} samples to {cache_path}")
except OSError:
pass
def _find_classes(self, root_list):
classes = set()
for root in root_list:
classes.update(d.name for d in os.scandir(root) if d.is_dir())
classes = sorted(classes)
return classes, {c: i for i, c in enumerate(classes)}
def _make_dataset(self, root_list):
samples = []
for root in root_list:
for entry in os.scandir(root):
if not entry.is_dir(): continue
cls_idx = self.class_to_idx.get(entry.name)
if cls_idx is None: continue
for fentry in os.scandir(entry.path):
if os.path.splitext(fentry.name)[1].lower() in self.VALID_EXTS:
samples.append((fentry.path, cls_idx))
return samples
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
path, target = self.samples[index]
img = _fast_loader(path)
if self.transform is not None:
img = self.transform(img)
return img, target
class DataFactory:
STATS = {
'cifar10': ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
'cifar100': ((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2762)),
'svhn': ((0.4377, 0.4438, 0.4728), (0.1980, 0.2010, 0.1970)),
'tiny_imagenet': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
'flowers102': ((0.4330, 0.3819, 0.2964), (0.2485, 0.2201, 0.2319)),
'imagenet1k': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
'imagenet100': ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
}
@classmethod
def calculate_dataset_stats(cls, dataset, batch_size=256, num_workers=4):
print("Calculating dataset mean and std dynamically (this may take a moment)...")
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)
sum_ = None
sum_of_squares = None
total_pixels = 0
for images, _ in loader:
C = images.size(1)
if sum_ is None:
sum_ = torch.zeros(C)
sum_of_squares = torch.zeros(C)
sum_ += images.sum(dim=[0, 2, 3])
sum_of_squares += (images ** 2).sum(dim=[0, 2, 3])
total_pixels += images.size(0) * images.size(2) * images.size(3)
mean = sum_ / total_pixels
var = (sum_of_squares / total_pixels) - (mean ** 2)
std = torch.sqrt(torch.clamp(var, min=1e-6))
return mean.tolist(), std.tolist()
@classmethod
def _get_raw_dataset(cls, ds, config, transform):
if ds == 'cifar10':
return torchvision.datasets.CIFAR10(config.data_dir, train=True, download=True, transform=transform)
elif ds == 'cifar100':
return torchvision.datasets.CIFAR100(config.data_dir, train=True, download=True, transform=transform)
elif ds == 'svhn':
return torchvision.datasets.SVHN(config.data_dir, split='train', download=True, transform=transform)
elif ds == 'tiny_imagenet':
train_dir, _ = cls.prepare_tiny_imagenet(config.data_dir)
return torchvision.datasets.ImageFolder(train_dir, transform=transform)
elif ds in ('imagenet1k', 'imagenet100'):
train_dir = os.path.join(config.data_dir, 'train')
if os.path.exists(train_dir):
cache_dir = _get_writable_cache_dir()
return FastImageFolder([train_dir], transform=transform,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
prefix = 'imagenet' if ds == 'imagenet1k' else 'imagenet100'
train_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'train') for i in range(1, 5)]
train_roots = [r for r in train_roots if os.path.exists(r)]
cache_dir = _get_writable_cache_dir()
return FastImageFolder(train_roots, transform=transform,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
elif ds == 'flowers102':
return torchvision.datasets.Flowers102(config.data_dir, split='train', download=True, transform=transform)
else:
raise ValueError(f"Unknown dataset {ds}")
@staticmethod
def prepare_tiny_imagenet(input_dir):
is_master = True
working_dir = "/kaggle/working/tiny_imagenet_data"
base_dir = os.path.join(working_dir, "tiny-imagenet-200")
# Handle Kaggle input path logic
kaggle_src = os.path.join(input_dir, "tiny-imagenet-200")
if not os.path.exists(kaggle_src) and "tiny-imagenet-200" in input_dir:
kaggle_src = input_dir
if os.path.exists(kaggle_src):
# OPTIMIZATION 1: Zero-Copy Training Data
# Read the training data directly from the read-only Kaggle input.
# PyTorch's ImageFolder works perfectly fine pointing to read-only directories.
train_dir = os.path.join(kaggle_src, 'train')
# OPTIMIZATION 2: Symlink Validation Data
# Instead of copying, we create empty folders and map virtual symbolic
# links to the read-only files. This takes milliseconds.
val_dir = os.path.join(base_dir, 'val')
if is_master and not os.path.exists(val_dir):
print("Creating fast symlinks for validation set...")
os.makedirs(val_dir, exist_ok=True)
val_images_src = os.path.join(kaggle_src, 'val', 'images')
val_annotations = os.path.join(kaggle_src, 'val', 'val_annotations.txt')
with open(val_annotations, 'r') as f:
lines = f.readlines()
# Pre-create the 200 class directories (faster than doing it in the image loop)
unique_classes = set(line.strip().split('\t')[1] for line in lines)
for class_id in unique_classes:
os.makedirs(os.path.join(val_dir, class_id), exist_ok=True)
# Create symlinks mapping to the read-only original files
for line in lines:
img_name, class_id = line.strip().split('\t')[:2]
src_img = os.path.join(val_images_src, img_name)
dst_img = os.path.join(val_dir, class_id, img_name)
if not os.path.exists(dst_img):
os.symlink(src_img, dst_img)
else:
# Fallback if the dataset isn't mounted and we MUST download it
train_dir = os.path.join(base_dir, 'train')
val_dir = os.path.join(base_dir, 'val')
if is_master and not os.path.exists(base_dir):
os.makedirs(working_dir, exist_ok=True)
print("Downloading TinyImageNet...")
zip_path = os.path.join(working_dir, "tiny.zip")
urllib.request.urlretrieve("http://cs231n.stanford.edu/tiny-imagenet-200.zip", zip_path)
# OPTIMIZATION 3: Native Extraction
# System `unzip` is 10x+ faster than Python's `zipfile` module for small files
print("Extracting via system unzip...")
subprocess.run(['unzip', '-q', zip_path, '-d', working_dir], check=True)
os.remove(zip_path)
# Restructure downloaded val data
print("Restructuring downloaded validation set...")
val_images_dir = os.path.join(val_dir, 'images')
val_annotations = os.path.join(val_dir, 'val_annotations.txt')
with open(val_annotations, 'r') as f:
lines = f.readlines()
unique_classes = set(line.strip().split('\t')[1] for line in lines)
for class_id in unique_classes:
os.makedirs(os.path.join(val_dir, class_id), exist_ok=True)
for line in lines:
img_name, class_id = line.strip().split('\t')[:2]
src_img = os.path.join(val_images_dir, img_name)
dst_img = os.path.join(val_dir, class_id, img_name)
if os.path.exists(src_img):
os.rename(src_img, dst_img)
shutil.rmtree(val_images_dir)
os.remove(val_annotations)
return train_dir, val_dir
@classmethod
def get_dataloaders(cls, config):
ds = config.dataset.lower()
if ds.startswith('vtab_'):
from vtab_datasets import download_vtab, VTABDataFactory
task_name = ds.split('vtab_')[1]
vtab_dir = download_vtab(config.data_dir)
train_loader, test_loader, num_classes = VTABDataFactory.get_dataloaders(
task_name, vtab_dir, img_size=config.img_size, batch_size=config.batch_size,
num_workers=config.num_workers,
)
config.num_classes = num_classes # Dynamically set num classes
return train_loader, test_loader, len(train_loader.dataset), len(test_loader.dataset)
os.makedirs(config.data_dir, exist_ok=True)
img_size = config.img_size
if ds not in cls.STATS:
print(f"Dataset '{ds}' stats not found. Calculating dynamically...")
temp_tf = transforms.Compose([
transforms.Resize((img_size, img_size)),
transforms.ToTensor()
])
temp_dataset = cls._get_raw_dataset(ds, config, temp_tf)
mean, std = cls.calculate_dataset_stats(temp_dataset, num_workers=config.num_workers)
cls.STATS[ds] = (mean, std)
print(f"Calculated stats for '{ds}':\n Mean: {mean}\n Std: {std}")
mean, std = cls.STATS[ds]
padding = max(4, img_size // 8)
train_tf = transforms.Compose([
transforms.Resize((img_size, img_size)),
transforms.RandomCrop(img_size, padding=padding, padding_mode='reflect'),
transforms.RandomHorizontalFlip(),
transforms.RandAugment(num_ops=2, magnitude=9),
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
test_tf = transforms.Compose([
transforms.Resize((img_size, img_size)),
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
if ds == 'cifar10':
trainset = torchvision.datasets.CIFAR10(config.data_dir, train=True, download=True, transform=train_tf)
testset = torchvision.datasets.CIFAR10(config.data_dir, train=False, download=True, transform=test_tf)
elif ds == 'cifar100':
trainset = torchvision.datasets.CIFAR100(config.data_dir, train=True, download=True, transform=train_tf)
testset = torchvision.datasets.CIFAR100(config.data_dir, train=False, download=True, transform=test_tf)
elif ds == 'svhn':
trainset = torchvision.datasets.SVHN(config.data_dir, split='train', download=True, transform=train_tf)
testset = torchvision.datasets.SVHN(config.data_dir, split='test', download=True, transform=test_tf)
elif ds == 'tiny_imagenet':
train_dir, val_dir = cls.prepare_tiny_imagenet(config.data_dir)
trainset = torchvision.datasets.ImageFolder(train_dir, transform=train_tf)
testset = torchvision.datasets.ImageFolder(val_dir, transform=test_tf)
elif ds in ('imagenet1k', 'imagenet100'):
in1k_train_tf = transforms.Compose([
transforms.RandomResizedCrop(img_size),
transforms.RandomHorizontalFlip(),
transforms.RandAugment(num_ops=2, magnitude=9),
transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
transforms.ToTensor(),
transforms.Normalize(mean, std),
transforms.RandomErasing(p=0.25)
])
in1k_test_tf = transforms.Compose([
transforms.Resize(int(img_size * 1.14)),
transforms.CenterCrop(img_size),
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
train_dir = os.path.join(config.data_dir, 'train')
val_dir = os.path.join(config.data_dir, 'val')
cache_dir = _get_writable_cache_dir()
if os.path.exists(train_dir):
trainset = FastImageFolder([train_dir], transform=in1k_train_tf,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
testset = FastImageFolder([val_dir], transform=in1k_test_tf,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_val.pkl'))
else:
prefix = 'imagenet' if ds == 'imagenet1k' else 'imagenet100'
train_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'train') for i in range(1, 5)]
val_roots = [os.path.join(config.data_dir, f'{prefix}_part_{i}', 'val') for i in range(1, 5)]
valid_train = [r for r in train_roots if os.path.exists(r)]
valid_val = [r for r in val_roots if os.path.exists(r)]
if not valid_train:
raise FileNotFoundError(
f"No ImageNet directory partitions found at '{config.data_dir}'.\n"
f"If running locally, please edit Config.data_dir = 'data' and Config.dataset = 'cifar100' or 'tiny_imagenet'."
)
trainset = FastImageFolder(valid_train, transform=in1k_train_tf,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_train.pkl'))
testset = FastImageFolder(valid_val, transform=in1k_test_tf,
cache_path=os.path.join(cache_dir, f'.fif_{ds}_val.pkl'))
elif ds == 'flowers102':
trainset = torchvision.datasets.Flowers102(config.data_dir, split='train', download=True,
transform=train_tf)
testset = torchvision.datasets.Flowers102(config.data_dir, split='test', download=True, transform=test_tf)
else:
raise ValueError(f"Unknown dataset {ds}")
persistent = config.num_workers > 0
train_loader = DataLoader(trainset, batch_size=config.batch_size, shuffle=True,
num_workers=config.num_workers, prefetch_factor=config.prefetch_factor,
pin_memory=True, drop_last=True, persistent_workers=persistent)
test_loader = DataLoader(testset, batch_size=config.batch_size, shuffle=False,
num_workers=config.num_workers, prefetch_factor=config.prefetch_factor,
pin_memory=True, persistent_workers=persistent)
return train_loader, test_loader, len(trainset), len(testset)
# ==============================================================================
# ARCHITECTURE MODULES
# ==============================================================================
class ChannelAttention(nn.Module):
"""Channel attention with reduction ratio — negligible parameter overhead."""
def __init__(self, dim, reduction=16):
super().__init__()
self.pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(dim, dim // reduction, bias=False),
nn.GELU(),
nn.Linear(dim // reduction, dim, bias=False),
nn.Sigmoid()
)
def forward(self, x):
B, C, _, _ = x.shape
w = self.pool(x).view(B, C)
w = self.fc(w).view(B, C, 1, 1)
return x * w
class ConvBlock(nn.Module):
def __init__(self, dim):
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.pwconv1 = nn.Linear(dim, 4 * dim)
self.act = nn.GELU()
self.pwconv2 = nn.Linear(4 * dim, dim)
self.se = ChannelAttention(dim)
def forward(self, x):
input = x
x = self.dwconv(x)
x = x.permute(0, 2, 3, 1) # NCHW -> NHWC
x = self.norm(x)
x = self.pwconv1(x)
x = self.act(x)
x = self.pwconv2(x)
x = x.permute(0, 3, 1, 2) # NHWC -> NCHW
x = self.se(x)
return input + x
class FeaturePyramid(nn.Module):
def __init__(self, in_channels, channels):
super().__init__()
c1, c2, c3 = channels
self.stem = nn.Sequential(
nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False),
nn.BatchNorm2d(64),
nn.GELU(),
ConvBlock(64)
)
self.down1 = nn.Sequential(
nn.Conv2d(64, c3, kernel_size=2, stride=2), # 16x16
ConvBlock(c3)
)
self.down2 = nn.Sequential(
nn.Conv2d(c3, c2, kernel_size=2, stride=2), # 8x8
ConvBlock(c2)
)
self.down3 = nn.Sequential(
nn.Conv2d(c2, c1, kernel_size=2, stride=2), # 4x4
ConvBlock(c1)
)
def forward(self, x):
if x.is_cuda and not x.is_contiguous(memory_format=torch.channels_last):
x = x.to(memory_format=torch.channels_last)
x = self.stem(x)
f_fine = self.down1(x)
f_medium = self.down2(f_fine)
f_coarse = self.down3(f_medium)
return f_coarse, f_medium, f_fine
class DropPath(nn.Module):
"""Simple inline DropPath to avoid silent degradation if timm is missing."""
def __init__(self, drop_prob=0.0):
super().__init__()
self.drop_prob = drop_prob
def forward(self, x):
if not self.training or self.drop_prob == 0.:
return x
keep = 1 - self.drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
mask = x.new_empty(shape).bernoulli_(keep).div_(keep)
return x * mask
class LoopAdjuster(nn.Module):
def __init__(self, dim, r=16):
super().__init__()
self.down = nn.Linear(dim, r, bias=False)
self.act = nn.GELU()
self.up = nn.Linear(r, dim, bias=False)
nn.init.zeros_(self.up.weight)
def forward(self, x):
return self.up(self.act(self.down(x)))
class AttentionBlock(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, dropout=0.0, drop_path=0.0):
super().__init__()
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.heads = num_heads
self.head_dim = dim // num_heads
self.drop_p = dropout
self.norm1 = nn.LayerNorm(dim, eps=1e-6)
self.qkv = nn.Linear(dim, 3 * dim, bias=True)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(dropout)
self.msa_adjusters = nn.ModuleList([LoopAdjuster(dim) for _ in range(3)])
self.norm2 = nn.LayerNorm(dim, eps=1e-6)
mlp_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, mlp_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(mlp_dim, dim),
nn.Dropout(dropout)
)
self.mlp_adjusters = nn.ModuleList([LoopAdjuster(dim) for _ in range(3)])
def forward(self, x, sin, cos, loop_idx, cls_only=False):
if cls_only:
normed_x = self.norm1(x)
B, N, C = normed_x.shape
# Q only for CLS token (B, 1, C); K, V for all tokens (B, N, C)
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)
kv_lin = F.linear(normed_x, self.qkv.weight[C:], self.qkv.bias[C:] if self.qkv.bias is not None else None)
q = q_lin.reshape(B, 1, self.heads, self.head_dim).permute(0, 2, 1, 3)
kv = kv_lin.reshape(B, N, 2, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
k, v = kv[0], kv[1]
q = apply_rotary_pos_emb(q, sin[:, 0:1], cos[:, 0:1]).to(v.dtype).contiguous()
k = apply_rotary_pos_emb(k, sin, cos).to(v.dtype).contiguous()
v = v.contiguous()
attn_out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.drop_p if self.training else 0.0)
attn_out = attn_out.transpose(1, 2).reshape(B, 1, C)
x_cls = x[:, 0:1]
msa_out = self.proj_drop(self.proj(attn_out)) + self.msa_adjusters[loop_idx](x_cls)
x_cls = x_cls + self.drop_path(msa_out)
normed_cls = self.norm2(x_cls)
mlp_out = self.mlp(normed_cls) + self.mlp_adjusters[loop_idx](normed_cls)
return x_cls + self.drop_path(mlp_out)
normed_x = self.norm1(x)
qkv = self.qkv(normed_x)
B, N, C = normed_x.shape
qkv = qkv.reshape(B, N, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
q = apply_rotary_pos_emb(q, sin, cos).to(v.dtype).contiguous()
k = apply_rotary_pos_emb(k, sin, cos).to(v.dtype).contiguous()
v = v.contiguous()
attn_out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.drop_p if self.training else 0.0)
attn_out = attn_out.transpose(1, 2).reshape(B, N, C)
msa_out = self.proj_drop(self.proj(attn_out)) + self.msa_adjusters[loop_idx](x)
x = x + self.drop_path(msa_out)
normed_x = self.norm2(x)
mlp_out = self.mlp(normed_x) + self.mlp_adjusters[loop_idx](normed_x)
x = x + self.drop_path(mlp_out)
return x
class RoPE2D(nn.Module):
def __init__(self, head_dim, base=10000.0):
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim // 2, 2).float() / (head_dim // 2)))
self.register_buffer('inv_freq', inv_freq)
def forward(self, coords):
x, y = coords[..., 0], coords[..., 1]
freqs_x = x.unsqueeze(-1) * self.inv_freq
freqs_y = y.unsqueeze(-1) * self.inv_freq
emb_x = torch.cat((freqs_x, freqs_x), dim=-1)
emb_y = torch.cat((freqs_y, freqs_y), dim=-1)
emb = torch.cat((emb_x, emb_y), dim=-1)
return torch.sin(emb), torch.cos(emb)
def apply_rotary_pos_emb(x, sin, cos):
sin = sin.unsqueeze(1)
cos = cos.unsqueeze(1)
q = x.shape[-1] // 4
x_rot = torch.cat([-x[..., q:2*q], x[..., :q], -x[..., 3*q:], x[..., 2*q:3*q]], dim=-1)
return torch.addcmul(x * cos, x_rot, sin)
def differentiable_topk(scores, K, tau=1.0, training=False):
"""
CVPR-standard Perturbed Top-K with Straight-Through Estimator.
Provides gradients to all elements via Gumbel-Softmax relaxation.
Bypasses STE computation during inference (training=False) for speed.
"""
B, N = scores.shape
if training:
gumbels = -torch.empty_like(scores).exponential_().log()
perturbed = scores + gumbels
else:
perturbed = scores
# Use argsort to get both top and bottom K in a single pass, avoiding slow kthvalue
sorted_idx = torch.argsort(perturbed, dim=-1, descending=True)
topk_idx = sorted_idx[..., :K]
if N > K:
botk_idx = sorted_idx[..., K:]
else:
botk_idx = None
if training:
threshold = perturbed.gather(-1, topk_idx[..., -1:])
soft_mask = torch.sigmoid((perturbed - threshold) / tau)
hard_mask = torch.zeros_like(scores).scatter(-1, topk_idx, 1.0)
mask = hard_mask - soft_mask.detach() + soft_mask
else:
mask = None
return mask, topk_idx, botk_idx
def get_fvcore_flops(model, config, device=None):
"""
Profile full forward pass FLOPs / MACs using fvcore FlopCountAnalysis.
Counts 1 MAC = 1 FLOP as per fvcore standard.
"""
try:
from fvcore.nn import FlopCountAnalysis
if device is None:
device = next(model.parameters()).device
dummy = torch.randn(1, config.in_channels, config.img_size, config.img_size, device=device)
class _FullEval(nn.Module):
def __init__(self, m):
super().__init__()
self.m = m
def forward(self, x):
return self.m.forward_eval(x, max_loops=3)[0]
was_training = model.training
model.eval()
with torch.no_grad():
flops = FlopCountAnalysis(_FullEval(model), dummy).total()
if was_training:
model.train()
return float(flops)
except Exception:
return 0.0
class FoViT(nn.Module):
def __init__(self, config: Config):
super().__init__()
self.C = config
D = config.dim
c1, c2, c3 = D, D // 2, D // 4
self.pyramid = FeaturePyramid(config.in_channels, (c1, c2, c3))
self.proj_coarse = nn.Sequential(nn.LayerNorm(c1), nn.Linear(c1, D))
self.proj_medium = nn.Sequential(nn.LayerNorm(c2), nn.Linear(c2, D))
self.proj_fine = nn.Sequential(nn.LayerNorm(c3), nn.Linear(c3, D))
h_c, h_m, h_f = config.img_size // 16, config.img_size // 8, config.img_size // 4
def build_coords(h, scale, offset):
r = torch.arange(h)
c = torch.arange(h)
grid_r, grid_c = torch.meshgrid(r, c, indexing='ij')
coords = torch.stack([grid_r * scale + offset, grid_c * scale + offset], dim=-1).flatten(0, 1)
return coords.float()
self.register_buffer('coords_c', build_coords(h_c, 16, 8))
self.register_buffer('coords_m', build_coords(h_m, 8, 4))
self.register_buffer('coords_f', build_coords(h_f, 4, 2))
self.rope = RoPE2D(D // config.num_heads)
self.modulate_c2m = nn.Linear(D, 2 * D)
self.modulate_m2f = nn.Linear(D, 2 * D)
self.register_buffer('c2m_idx', self._build_hierarchy_map(h_c, h_c, h_m, h_m))
self.register_buffer('m2f_idx', self._build_hierarchy_map(h_m, h_m, h_f, h_f))
# Pre-compute static coordinate & RoPE grids for all loops (persistent=False preserves checkpoint keys)
cls_coord = torch.full((1, 1, 2), -1.0)
coord0_static = torch.cat([cls_coord, self.coords_c.unsqueeze(0)], dim=1)
sin0_static, cos0_static = self.rope(coord0_static)
self.register_buffer('sin0_static', sin0_static, persistent=False)
self.register_buffer('cos0_static', cos0_static, persistent=False)
sin_m_static, cos_m_static = self.rope(self.coords_m.unsqueeze(0))
self.register_buffer('sin_m_static', sin_m_static, persistent=False)
self.register_buffer('cos_m_static', cos_m_static, persistent=False)
sin_f_static, cos_f_static = self.rope(self.coords_f.unsqueeze(0))
self.register_buffer('sin_f_static', sin_f_static, persistent=False)
self.register_buffer('cos_f_static', cos_f_static, persistent=False)
self.cls_token = nn.Parameter(torch.zeros(1, 1, D))
self.scale_embed_c = nn.Parameter(torch.zeros(1, 1, D))
self.scale_embed_m = nn.Parameter(torch.zeros(1, 1, D))
self.scale_embed_f = nn.Parameter(torch.zeros(1, 1, D))
self.loop_embed = nn.Embedding(3, D)
# Pre-cache loop index tensors to avoid re-allocating every forward pass
self.register_buffer('_loop_ids', torch.arange(3))
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.depth)]
self.blocks = nn.ModuleList([
AttentionBlock(D, config.num_heads, config.mlp_ratio, config.dropout, drop_path=dpr[i])
for i in range(config.depth)
])
# CLS-to-patch gated broadcast — improves patch representations
self.cls_gate = nn.Sequential(nn.Linear(D, D), nn.Sigmoid())
self.norm = nn.LayerNorm(D, eps=1e-6)
self.head = nn.Linear(D, config.num_classes)
self.score_proj = nn.ModuleList([nn.Linear(D, 1) for _ in range(2)])
self._init_weights()
def _build_hierarchy_map(self, hc, wc, hm, wm):
# Fully vectorized: compute all parent (r,c) pairs at once
idx = torch.arange(hc * wc)
r = (idx // wc).unsqueeze(1) # (N,1)
c = (idx % wc).unsqueeze(1) # (N,1)
dr = torch.tensor([0, 0, 1, 1])
dc = torch.tensor([0, 1, 0, 1])
return ((2 * r + dr) * wm + (2 * c + dc)).long() # (N,4)
def _init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.trunc_normal_(m.weight, std=0.02)
if m.bias is not None: nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.trunc_normal_(m.weight, std=0.02)
nn.init.trunc_normal_(self.cls_token, std=0.02)
nn.init.trunc_normal_(self.scale_embed_c, std=0.02)
nn.init.trunc_normal_(self.scale_embed_m, std=0.02)
nn.init.trunc_normal_(self.scale_embed_f, std=0.02)
def _tokenize(self, feat, proj):
tokens = feat.flatten(2).transpose(1, 2)
return proj(tokens)
def _loop(self, seq, sin, cos, loop_idx):
B = seq.shape[0]
c_ids = self._loop_ids[loop_idx].expand(B)
c = self.loop_embed(c_ids).unsqueeze(1)
seq = seq + c
for blk_idx, blk in enumerate(self.blocks):
if loop_idx == 2 and blk_idx == len(self.blocks) - 1:
# Last block of Loop 2: CLS-only query & MLP optimization (Optimization 3A)
return blk(seq, sin, cos, loop_idx, cls_only=True)
if self.training and getattr(self.C, 'use_grad_checkpointing', False):
seq = torch.utils.checkpoint.checkpoint(blk, seq, sin, cos, loop_idx, use_reentrant=False)
else:
seq = blk(seq, sin, cos, loop_idx)
# CLS-to-patch gated broadcast
gate = self.cls_gate(seq[:, 0:1])
seq = torch.cat([seq[:, 0:1], seq[:, 1:] + gate * seq[:, 0:1]], dim=1)
return seq
def forward_train(self, x, tau=1.0):
B = x.shape[0]
D = self.C.dim
N_c = (self.C.img_size // 16) ** 2
D_head = self.sin0_static.shape[-1]
f_c, f_m, f_f = self.pyramid(x)
t_c = self._tokenize(f_c, self.proj_coarse) + self.scale_embed_c
cls = self.cls_token.expand(B, -1, -1)
sin_cls = self.sin0_static[:, 0:1, :].expand(B, -1, -1)
cos_cls = self.cos0_static[:, 0:1, :].expand(B, -1, -1)
# --- Loop 0 ---
seq0 = torch.cat([cls, t_c], 1)
sin0 = self.sin0_static.expand(B, -1, -1)
cos0 = self.cos0_static.expand(B, -1, -1)
seq0_out = self._loop(seq0, sin0, cos0, 0)
seq0_normed = self.norm(seq0_out)
l0 = self.head(seq0_normed[:, 0])
# Saliency on Coarse
cls0_out = seq0_out[:, 0:1, :]
tc0_out = seq0_out[:, 1:1 + N_c, :]
cls0_normed = seq0_normed[:, 0:1, :]
tc0_normed = seq0_normed[:, 1:1 + N_c, :]
saliency_c = torch.clamp(self.score_proj[0](tc0_normed * cls0_normed).squeeze(-1), min=-50.0, max=50.0)
mask_c, topk_c, botk_c = differentiable_topk(saliency_c, self.C.K1, tau=tau, training=self.training)
# Sort selected indices for coalesced GPU memory access
topk_c, _ = torch.sort(topk_c, dim=-1)
selected_m_idx = self.c2m_idx[topk_c].view(B, -1)
# Gather-first projection: project only selected medium patches
feat_m = f_m.flatten(2).transpose(1, 2)
selected_m_raw = feat_m.gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, feat_m.shape[-1]))
selected_m_tokens = self.proj_medium(selected_m_raw) + self.scale_embed_m
# Precomputed RoPE gather for medium patches
sin_m_selected = self.sin_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
cos_m_selected = self.cos_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
top_mask_c = mask_c.gather(1, topk_c).unsqueeze(-1)
context_c = tc0_out.gather(1, topk_c.unsqueeze(-1).expand(-1, -1, D)) * top_mask_c
gb_c = self.modulate_c2m(context_c).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
gamma_c, beta_c = gb_c.chunk(2, dim=-1)
selected_m_tokens = selected_m_tokens * (1 + gamma_c) + beta_c
num_retained_c = N_c - self.C.K1
if num_retained_c > 0:
bot_mask_c = (1.0 - mask_c).gather(1, botk_c).unsqueeze(-1)
retained_c_tokens = tc0_out.gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D)) * bot_mask_c
sin_c_retained = self.sin0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
cos_c_retained = self.cos0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
seq1 = torch.cat([cls0_out, retained_c_tokens, selected_m_tokens], dim=1)
sin1 = torch.cat([sin_cls, sin_c_retained, sin_m_selected], dim=1)
cos1 = torch.cat([cos_cls, cos_c_retained, cos_m_selected], dim=1)
else:
seq1 = torch.cat([cls0_out, selected_m_tokens], dim=1)
sin1 = torch.cat([sin_cls, sin_m_selected], dim=1)
cos1 = torch.cat([cos_cls, cos_m_selected], dim=1)
# --- Loop 1 ---
seq1_out = self._loop(seq1, sin1, cos1, 1)
seq1_normed = self.norm(seq1_out)
l1 = self.head(seq1_normed[:, 0])
cls1_out = seq1_out[:, 0:1, :]
tm1_out = seq1_out[:, 1 + num_retained_c:, :]
cls1_normed = seq1_normed[:, 0:1, :]
tm1_normed = seq1_normed[:, 1 + num_retained_c:, :]
saliency_m = torch.clamp(self.score_proj[1](tm1_normed * cls1_normed).squeeze(-1), min=-50.0, max=50.0)
mask_m, topk_m_local, botk_m = differentiable_topk(saliency_m, self.C.K2, tau=tau, training=self.training)
# Sort selected local indices for coalesced GPU memory access
topk_m_local, _ = torch.sort(topk_m_local, dim=-1)
global_m_idx = selected_m_idx.gather(1, topk_m_local)
selected_f_idx = self.m2f_idx[global_m_idx].view(B, -1)
# Gather-first projection: project only selected fine patches
feat_f = f_f.flatten(2).transpose(1, 2)
selected_f_raw = feat_f.gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, feat_f.shape[-1]))
selected_f_tokens = self.proj_fine(selected_f_raw) + self.scale_embed_f
# Precomputed RoPE gather for fine patches
sin_f_selected = self.sin_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
cos_f_selected = self.cos_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
top_mask_m = mask_m.gather(1, topk_m_local).unsqueeze(-1)
context_m = tm1_out.gather(1, topk_m_local.unsqueeze(-1).expand(-1, -1, D)) * top_mask_m
gb_m = self.modulate_m2f(context_m).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
gamma_m, beta_m = gb_m.chunk(2, dim=-1)
selected_f_tokens = selected_f_tokens * (1 + gamma_m) + beta_m
num_m = 4 * self.C.K1
num_retained_m = num_m - self.C.K2
if num_retained_m > 0:
bot_mask_m = (1.0 - mask_m).gather(1, botk_m).unsqueeze(-1)
retained_m_tokens = tm1_out.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D)) * bot_mask_m
sin_m_retained = sin_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
cos_m_retained = cos_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
if num_retained_c > 0:
retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
seq2 = torch.cat([cls1_out, retained_c_out, retained_m_tokens, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_c_retained, sin_m_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_c_retained, cos_m_retained, cos_f_selected], dim=1)
else:
seq2 = torch.cat([cls1_out, retained_m_tokens, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_m_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_m_retained, cos_f_selected], dim=1)
else:
if num_retained_c > 0:
retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
seq2 = torch.cat([cls1_out, retained_c_out, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_c_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_c_retained, cos_f_selected], dim=1)
else:
seq2 = torch.cat([cls1_out, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_f_selected], dim=1)
# --- Loop 2 ---
seq2_out = self._loop(seq2, sin2, cos2, 2)
l2 = self.head(self.norm(seq2_out[:, 0]))
entropy_loss = -torch.mean(F.softmax(saliency_c, dim=-1) * F.log_softmax(saliency_c, dim=-1))
entropy_loss += -torch.mean(F.softmax(saliency_m, dim=-1) * F.log_softmax(saliency_m, dim=-1))
stats = {
'sal_c_mean': saliency_c.mean(),
'sal_c_std': saliency_c.std(),
'sal_m_mean': saliency_m.mean(),
'sal_m_std': saliency_m.std()
}
return torch.stack([l0, l1, l2]), entropy_loss, stats
@torch.no_grad()
def forward_eval(self, x, exit_conf=0.9, max_loops=None, visualize=False, return_saliency=False):
B = x.shape[0]
D = self.C.dim
N_c = (self.C.img_size // 16) ** 2
D_head = self.sin0_static.shape[-1]
f_c, f_m, f_f = self.pyramid(x)
t_c = self._tokenize(f_c, self.proj_coarse) + self.scale_embed_c
cls = self.cls_token.expand(B, -1, -1)
sin_cls = self.sin0_static[:, 0:1, :].expand(B, -1, -1)
cos_cls = self.cos0_static[:, 0:1, :].expand(B, -1, -1)
# L0
seq0 = torch.cat([cls, t_c], 1)
sin0 = self.sin0_static.expand(B, -1, -1)
cos0 = self.cos0_static.expand(B, -1, -1)
seq0_out = self._loop(seq0, sin0, cos0, 0)
seq0_normed = self.norm(seq0_out)
l0 = self.head(seq0_normed[:, 0])
conf0 = F.softmax(l0, -1).max(-1).values
done0 = conf0 >= exit_conf
if (max_loops == 1 or done0.all()) and not visualize and not return_saliency:
return l0, torch.ones(B, device=l0.device), 0.0
# L1
cls0_out = seq0_out[:, 0:1, :]
tc0_out = seq0_out[:, 1:1 + N_c, :]
cls0_normed = seq0_normed[:, 0:1, :]
tc0_normed = seq0_normed[:, 1:1 + N_c, :]
saliency_c = torch.clamp(self.score_proj[0](tc0_normed * cls0_normed).squeeze(-1), min=-50.0, max=50.0)
_, topk_c, botk_c = differentiable_topk(saliency_c, self.C.K1, tau=1.0, training=self.training)
# Sort selected indices for coalesced GPU memory access
topk_c, _ = torch.sort(topk_c, dim=-1)
selected_m_idx = self.c2m_idx[topk_c].view(B, -1)
feat_m = f_m.flatten(2).transpose(1, 2)
selected_m_raw = feat_m.gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, feat_m.shape[-1]))
selected_m_tokens = self.proj_medium(selected_m_raw) + self.scale_embed_m
# Fast RoPE gather (no dynamic trigonometry)
sin_m_selected = self.sin_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
cos_m_selected = self.cos_m_static.expand(B, -1, -1).gather(1, selected_m_idx.unsqueeze(-1).expand(-1, -1, D_head))
# In inference, mask is mathematically 1.0 (STE bypass)
context_c = tc0_out.gather(1, topk_c.unsqueeze(-1).expand(-1, -1, D))
gb_c = self.modulate_c2m(context_c).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
gamma_c, beta_c = gb_c.chunk(2, dim=-1)
selected_m_tokens = selected_m_tokens * (1 + gamma_c) + beta_c
num_retained_c = N_c - self.C.K1
if num_retained_c > 0:
retained_c_tokens = tc0_out.gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D))
sin_c_retained = self.sin0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
cos_c_retained = self.cos0_static[:, 1:, :].expand(B, -1, -1).gather(1, botk_c.unsqueeze(-1).expand(-1, -1, D_head))
seq1 = torch.cat([cls0_out, retained_c_tokens, selected_m_tokens], dim=1)
sin1 = torch.cat([sin_cls, sin_c_retained, sin_m_selected], dim=1)
cos1 = torch.cat([cos_cls, cos_c_retained, cos_m_selected], dim=1)
else:
seq1 = torch.cat([cls0_out, selected_m_tokens], dim=1)
sin1 = torch.cat([sin_cls, sin_m_selected], dim=1)
cos1 = torch.cat([cos_cls, cos_m_selected], dim=1)
seq1_out = self._loop(seq1, sin1, cos1, 1)
seq1_normed = self.norm(seq1_out)
l1 = self.head(seq1_normed[:, 0])
conf1 = F.softmax(l1, -1).max(-1).values
done1 = (conf1 >= exit_conf) | done0
if (max_loops == 2 or done1.all()) and not visualize and not return_saliency:
out = torch.where(done0.unsqueeze(-1), l0, l1)
loops = 1.0 * done0 + 2.0 * (~done0)
return out, loops.float(), 0.0
# L2
cls1_out = seq1_out[:, 0:1, :]
tm1_out = seq1_out[:, 1 + num_retained_c:, :]
cls1_normed = seq1_normed[:, 0:1, :]
tm1_normed = seq1_normed[:, 1 + num_retained_c:, :]
saliency_m = torch.clamp(self.score_proj[1](tm1_normed * cls1_normed).squeeze(-1), min=-50.0, max=50.0)
_, topk_m_local, botk_m = differentiable_topk(saliency_m, self.C.K2, tau=1.0, training=self.training)
# Sort selected local indices for coalesced GPU memory access
topk_m_local, _ = torch.sort(topk_m_local, dim=-1)
global_m_idx = selected_m_idx.gather(1, topk_m_local)
selected_f_idx = self.m2f_idx[global_m_idx].view(B, -1)
feat_f = f_f.flatten(2).transpose(1, 2)
selected_f_raw = feat_f.gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, feat_f.shape[-1]))
selected_f_tokens = self.proj_fine(selected_f_raw) + self.scale_embed_f
sin_f_selected = self.sin_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
cos_f_selected = self.cos_f_static.expand(B, -1, -1).gather(1, selected_f_idx.unsqueeze(-1).expand(-1, -1, D_head))
context_m = tm1_out.gather(1, topk_m_local.unsqueeze(-1).expand(-1, -1, D))
gb_m = self.modulate_m2f(context_m).unsqueeze(2).expand(-1, -1, 4, -1).reshape(B, -1, 2 * D)
gamma_m, beta_m = gb_m.chunk(2, dim=-1)
selected_f_tokens = selected_f_tokens * (1 + gamma_m) + beta_m
num_m = 4 * self.C.K1
num_retained_m = num_m - self.C.K2
if num_retained_m > 0:
retained_m_tokens = tm1_out.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D))
sin_m_retained = sin_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
cos_m_retained = cos_m_selected.gather(1, botk_m.unsqueeze(-1).expand(-1, -1, D_head))
if num_retained_c > 0:
retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
seq2 = torch.cat([cls1_out, retained_c_out, retained_m_tokens, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_c_retained, sin_m_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_c_retained, cos_m_retained, cos_f_selected], dim=1)
else:
seq2 = torch.cat([cls1_out, retained_m_tokens, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_m_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_m_retained, cos_f_selected], dim=1)
else:
if num_retained_c > 0:
retained_c_out = seq1_out[:, 1:1 + num_retained_c, :]
seq2 = torch.cat([cls1_out, retained_c_out, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_c_retained, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_c_retained, cos_f_selected], dim=1)
else:
seq2 = torch.cat([cls1_out, selected_f_tokens], dim=1)
sin2 = torch.cat([sin_cls, sin_f_selected], dim=1)
cos2 = torch.cat([cos_cls, cos_f_selected], dim=1)
seq2_out = self._loop(seq2, sin2, cos2, 2)
l2 = self.head(self.norm(seq2_out[:, 0]))
if visualize:
return l2, 3.0, (topk_c[0].cpu().tolist(), global_m_idx[0].cpu().tolist())
out = torch.where(done0.unsqueeze(-1), l0, torch.where(done1.unsqueeze(-1), l1, l2))
loops = 1.0 * done0 + 2.0 * (done1 & ~done0) + 3.0 * (~done1)
if return_saliency:
return out, loops.float(), (topk_c, global_m_idx)
return out, loops.float(), 0.0
def forward(self, x, tau=1.0, exit_conf=0.9):
if self.training:
return self.forward_train(x, tau=tau)
with torch.no_grad():
return self.forward_eval(x, exit_conf=exit_conf)[0]
# Alias for backward compatibility
RemSViT = FoViT
# ==============================================================================
# TRAINING
# ==============================================================================
def get_param_groups(model, lr, weight_decay, lr_decay=0.65):
"""Layer-wise LR decay: backbone gets lower LR, head gets full LR."""
no_decay = {'bias', 'norm', 'LayerNorm', 'BatchNorm'}
backbone_params = []
head_params = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue
is_backbone = 'pyramid' in name or 'blocks' in name
wd = 0.0 if any(nd in name for nd in no_decay) else weight_decay
if is_backbone:
backbone_params.append({'params': param, 'lr': lr * lr_decay, 'weight_decay': wd})
else:
head_params.append({'params': param, 'lr': lr, 'weight_decay': wd})
return backbone_params + head_params
def load_matched_state_dict(model: nn.Module, state_or_path, device=None):
"""
Load state dict into model with proper head handling:
- Retains and loads checkpoint head if shape matches model.head.
- Replaces and re-initializes head ONLY on dimension/shape mismatch or absence.
- Robust to legacy prefixes, DDP wrappers, and EMA dictionaries.
"""
if isinstance(state_or_path, str):
if not os.path.exists(state_or_path):
print(f" [WARN] Checkpoint not found at {state_or_path}. Skipping.")
return {}, {}, False
state = torch.load(state_or_path, map_location=device or 'cpu')
else:
state = state_or_path
# Unwrap checkpoint dictionary prioritizing EMA first
if isinstance(state, dict):
if 'ema' in state and isinstance(state['ema'], dict) and any(k.endswith('head.weight') for k in state['ema']):
state = state['ema']
elif 'model' in state and isinstance(state['model'], dict):
state = state['model']
elif 'state_dict' in state and isinstance(state['state_dict'], dict):
state = state['state_dict']
key_mappings = {
"_orig_mod.": "",
"module.": "",
"film_c2m": "modulate_c2m",
"film_m2f": "modulate_m2f",
"score_head": "score_proj",
"saliency_head": "score_proj",
"saliency_proj": "score_proj",
"stem_pyramid": "pyramid",
"fovea_blocks": "blocks",
}
new_state = {}
for k, v in state.items():
clean_k = k
for old_name, new_name in key_mappings.items():
clean_k = clean_k.replace(old_name, new_name)
new_state[clean_k] = v
state = new_state
model_state = model.state_dict()
matched_state = {}
head_mismatch = False
for k, v in state.items():
if k in model_state:
if model_state[k].shape == v.shape:
matched_state[k] = v
else:
if k.startswith("head."):
head_mismatch = True
print(f" [Head Mismatch] Checkpoint '{k}' shape {list(v.shape)} != model shape {list(model_state[k].shape)}. Head will be replaced.")
else:
print(f" [WARN] Shape mismatch for '{k}': checkpoint {list(v.shape)} vs model {list(model_state[k].shape)}")
else:
suffix_matches = [mk for mk in model_state if
(mk.endswith("." + k) or k.endswith("." + mk)) and not mk.startswith("head.")]
if len(suffix_matches) == 1 and model_state[suffix_matches[0]].shape == v.shape:
matched_state[suffix_matches[0]] = v
missing, unexpected = model.load_state_dict(matched_state, strict=False)
non_head_missing = [k for k in missing if not k.startswith("head.")]
if non_head_missing:
print(f" [WARN] Missing backbone keys: {non_head_missing}")
if unexpected:
print(f" [WARN] Unexpected keys in checkpoint: {unexpected}")
# Head replacement logic: replace ONLY if missing or mismatched
has_head_weight = 'head.weight' in matched_state
has_head_bias = ('head.bias' in matched_state) or (getattr(model.head, 'bias', None) is None)
head_matched = has_head_weight and has_head_bias
if not head_matched:
nn.init.trunc_normal_(model.head.weight, std=0.02)
if getattr(model.head, 'bias', None) is not None:
nn.init.zeros_(model.head.bias)
reason = "shape mismatch" if head_mismatch else "missing in checkpoint"
print(f" [Head Replacement] Head re-initialized for {model.head.out_features} classes ({reason}).")
else:
print(f" [Head Preserved] Kept checkpoint classification head ({model.head.out_features} classes matched).")
loaded_count = len(matched_state)
total_backbone_keys = len([k for k in model_state if not k.startswith("head.")])
src_desc = state_or_path if isinstance(state_or_path, str) else "state_dict"
print(f" Weights loaded successfully from: {src_desc} ({loaded_count}/{total_backbone_keys} backbone parameters matched)")
return missing, unexpected, head_matched
def load_pretrained_backbone(model: FoViT, checkpoint_path: str, device):
"""Backwards-compatible wrapper calling load_matched_state_dict."""
return load_matched_state_dict(model, checkpoint_path, device=device)
def train(C: Config, model_state_dict=None, return_dict=None, dataloaders=None, model=None):
is_master = True
# 1. Apply seed before doing anything stochastic (dataloaders, model init)
if hasattr(C, 'seed'):
set_seed(C.seed)
device = C.device
dtype = torch.bfloat16 if device.type != 'mps' else torch.float32
def ema_avg_fn(avg_param, param, num_avg):
decay = min(C.ema_decay, (1 + num_avg) / (10 + num_avg))
return avg_param * decay + param * (1 - decay)
if dataloaders is not None:
train_loader, test_loader, num_train, num_test = dataloaders
else:
train_loader, test_loader, num_train, num_test = DataFactory.get_dataloaders(C)
nvml_handle = None
if is_master:
try:
if pynvml is not None:
pynvml.nvmlInit()
nvml_handle = pynvml.nvmlDeviceGetHandleByIndex(0)
except Exception:
pass
if model is not None:
raw_model = model.to(device)
else:
raw_model = FoViT(C).to(device)
if getattr(C, 'pretrained_path', None) is not None and model_state_dict is None:
load_pretrained_backbone(raw_model, C.pretrained_path, device)
# --------------------------------------------
if model_state_dict is not None:
load_matched_state_dict(raw_model, model_state_dict, device=device)
model = raw_model
if hasattr(torch, 'compile'):
try:
model = torch.compile(raw_model)
except Exception:
pass
import inspect
ema_kwargs = {'avg_fn': ema_avg_fn, 'use_buffers': False}
ema = AveragedModel(raw_model, **ema_kwargs)
if is_master:
print(f"\nFoViT | Dataset: {C.dataset} | Device: {device}")
count_parameters(model)
backbone_scale = getattr(C, 'backbone_lr_scale', 1.0)
param_groups = get_param_groups(model, C.max_lr, C.weight_decay, lr_decay=backbone_scale)
optimizer = optim.AdamW(param_groups, lr=C.max_lr, weight_decay=C.weight_decay)
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
warmup_epochs = min(C.warmup_epochs, max(0, C.epochs - 1))
if warmup_epochs > 0:
warmup_sched = LinearLR(optimizer, start_factor=1e-3, total_iters=warmup_epochs)
cosine_sched = CosineAnnealingLR(optimizer, T_max=max(1, C.epochs - warmup_epochs), eta_min=C.lrmin)
scheduler = SequentialLR(optimizer, schedulers=[warmup_sched, cosine_sched], milestones=[warmup_epochs])
else:
scheduler = CosineAnnealingLR(optimizer, T_max=max(1, C.epochs), eta_min=C.lrmin)
if not os.path.exists(C.log_path):
with open(C.log_path, 'w', newline='') as f:
csv.writer(f).writerow(['Epoch', 'LR', 'Train_Loss', 'Loss_L0', 'Loss_L1', 'Loss_L2',
'Entropy_Loss', 'Sal_C_Mean', 'Sal_C_Std', 'Sal_M_Mean', 'Sal_M_Std',
'Test_Acc', 'Best_Acc', 'Epoch_Time_s'])
best_acc = 0.0
start_epoch = 1
loop_drop_start_epoch = C.warmup_epochs
if getattr(C, 'resume', False) and os.path.exists(getattr(C, 'checkpoint_path', '')):
if is_master:
print(f" [Checkpoint] Resuming from {C.checkpoint_path}...")
try:
ckpt = torch.load(C.checkpoint_path, map_location=device)
saved = ckpt.get('run_hparams')
if saved and (saved['max_lr'] != C.max_lr or saved['warmup_epochs'] != C.warmup_epochs or saved[
'epochs'] != C.epochs):
raise RuntimeError(
f"Config changed since checkpoint was saved ({saved} -> "
f"{{'max_lr': {C.max_lr}, 'warmup_epochs': {C.warmup_epochs}, 'epochs': {C.epochs}}}). "
f"Resuming would corrupt the LR schedule. Either revert Config or start a fresh run/checkpoint path."
)
loop_drop_start_epoch = ckpt.get('run_hparams', {}).get('warmup_epochs', C.warmup_epochs)
getattr(model, '_orig_mod', model).load_state_dict(ckpt['model'])
ema.load_state_dict(ckpt['ema'])
optimizer.load_state_dict(ckpt['optimizer'])
scheduler.load_state_dict(ckpt['scheduler'])
start_epoch = ckpt['epoch'] + 1
best_acc = ckpt.get('best_acc', 0.0)
if is_master:
print(f" [Checkpoint] Resumed at epoch {start_epoch} with best acc {best_acc:.2f}%")
except Exception as e:
if is_master:
print(f" [Checkpoint] Failed to load checkpoint: {e}")
if C.use_mixup:
mixup = v2.MixUp(alpha=0.5, num_classes=C.num_classes)
cutmix = v2.CutMix(alpha=0.5, num_classes=C.num_classes)
def apply_mix(inputs, targets):
r = torch.rand(1).item()
if r < 0.50:
return cutmix(inputs, targets) # CutMix dominant for ViTs
elif r < 0.80:
return mixup(inputs, targets)
return inputs, F.one_hot(targets, C.num_classes).float()
else:
def apply_mix(inputs, targets):
return inputs, F.one_hot(targets, C.num_classes).float()
# fvcore FLOP / MAC Profiling (1 MAC = 1 FLOP)
flops_forward_full = get_fvcore_flops(raw_model, C, device)
train_tflops_epoch = (3.0 * flops_forward_full * len(train_loader) * C.batch_size) / 1e12
eval_tflops_epoch = (flops_forward_full * len(test_loader) * C.batch_size) / 1e12
import time as _time
freeze_epochs = getattr(C, 'freeze_backbone_epochs', 0)
for epoch in range(start_epoch, C.epochs + 1):
epoch_start = _time.time()
model.train()
total_loss = 0.0
total_loss_l0 = 0.0
total_loss_l1 = 0.0
total_loss_l2 = 0.0
total_entropy = 0.0
sal_c_mean_sum, sal_c_std_sum = 0.0, 0.0
sal_m_mean_sum, sal_m_std_sum = 0.0, 0.0
# Backbone freeze stage: protect pretrained features from random head gradients
if freeze_epochs > 0:
_core = getattr(model, '_orig_mod', model)
if epoch <= freeze_epochs:
for name, p in _core.named_parameters():
if 'pyramid' in name or 'blocks' in name:
p.requires_grad_(False)
elif epoch == freeze_epochs + 1:
_core.requires_grad_(True)
print(f" [Epoch {epoch}] Backbone unfrozen — all parameters now trainable")
if epoch == start_epoch and is_master:
last_lr = scheduler.get_last_lr()[0] if hasattr(scheduler, 'get_last_lr') else optimizer.param_groups[0][
'lr']
print(
f" [Sanity Check] Starting/Resuming at Epoch: {epoch} | Scheduler Last Epoch: {scheduler.last_epoch} | Current LR: {last_lr:.2e}")
# Tau annealing: stay soft during warmup, then linearly harden over next 50 epochs
if epoch <= loop_drop_start_epoch:
tau_val = 1.0
else:
tau_val = max(0.1, 1.0 - (epoch - loop_drop_start_epoch) / 50.0)
tau = torch.tensor(tau_val, device=device, dtype=dtype)
start_train_energy = get_energy(nvml_handle)
optimizer.zero_grad(set_to_none=True)
for batch_idx, (inputs, targets) in enumerate(
tqdm(train_loader, desc=f"Epoch {epoch}/{C.epochs} Train", leave=False)):
inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
inputs, targets_mixed = apply_mix(inputs, targets)
with torch.autocast(device_type=device.type, dtype=dtype):
logits_stack, entropy_loss, stats = model(inputs, tau=tau)
l0, l1, l2 = logits_stack[0], logits_stack[1], logits_stack[2]
loss_l2_val = F.cross_entropy(l2, targets_mixed, label_smoothing=C.label_smoothing)
# Supervision for early exits
ce_l1 = F.cross_entropy(l1, targets_mixed, label_smoothing=C.label_smoothing)
ce_l0 = F.cross_entropy(l0, targets_mixed, label_smoothing=C.label_smoothing)
# Self-distillation: L2 teaches L1 and L0 via soft targets
T_dist = max(2.0, 4.0 * (1 - epoch / C.epochs))
soft_targets = F.softmax(l2.detach() / T_dist, dim=-1)
loss_l1_val = ce_l1 + F.kl_div(F.log_softmax(l1 / T_dist, dim=-1), soft_targets,
reduction='batchmean') * (T_dist ** 2)
loss_l0_val = ce_l0 + F.kl_div(F.log_softmax(l0 / T_dist, dim=-1), soft_targets,
reduction='batchmean') * (T_dist ** 2)
w_l1 = max(0.1, 0.5 * (1 - epoch / C.epochs))
w_l0 = max(0.05, 0.3 * (1 - epoch / C.epochs))
ent_weight = 0.01
loss = loss_l2_val + w_l1 * loss_l1_val + w_l0 * loss_l0_val + ent_weight * entropy_loss
loss = loss / getattr(C, 'accum_iter', 1)
total_loss += (loss * getattr(C, 'accum_iter', 1)).item()
total_loss_l0 += loss_l0_val.item()
total_loss_l1 += loss_l1_val.item()
total_loss_l2 += loss_l2_val.item()
total_entropy += entropy_loss.item()
sal_c_mean_sum += stats.get('sal_c_mean', torch.tensor(0.0, device=device)).item()
sal_c_std_sum += stats.get('sal_c_std', torch.tensor(0.0, device=device)).item()
sal_m_mean_sum += stats.get('sal_m_mean', torch.tensor(0.0, device=device)).item()
sal_m_std_sum += stats.get('sal_m_std', torch.tensor(0.0, device=device)).item()
loss.backward()
if ((batch_idx + 1) % getattr(C, 'accum_iter', 1) == 0) or (batch_idx + 1 == len(train_loader)):
torch.nn.utils.clip_grad_norm_(model.parameters(), C.grad_clip)
optimizer.step()
ema.update_parameters(raw_model)
optimizer.zero_grad(set_to_none=True)
# Step scheduler unconditionally once per epoch
scheduler.step()
end_train_energy = get_energy(nvml_handle)
train_energy_j = end_train_energy - start_train_energy
train_tflops = train_tflops_epoch
# Eval
ema.eval()
correct = total = 0
start_energy = get_energy(nvml_handle)
with torch.no_grad(), torch.autocast(device_type=device.type, dtype=dtype):
for inputs, targets in tqdm(test_loader, desc=f"Epoch {epoch} Eval", leave=False):
inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
logits = ema(inputs)
b_correct = logits.argmax(1).eq(targets).sum()
b_total = torch.tensor(targets.size(0), device=device)
total += b_total.item()
correct += b_correct.item()
end_energy = get_energy(nvml_handle)
energy_j = end_energy - start_energy
tflops = eval_tflops_epoch
acc = 100.0 * (correct.item() if isinstance(correct, torch.Tensor) else correct) / (
total.item() if isinstance(total, torch.Tensor) else total)
if acc > best_acc:
best_acc = acc
if is_master:
core = getattr(ema.module, '_orig_mod', ema.module)
torch.save(core.state_dict(), C.save_path)
n_batches = len(train_loader)
avg_loss = total_loss.item() / n_batches if isinstance(total_loss, torch.Tensor) else total_loss / n_batches
avg_l0 = total_loss_l0.item() / n_batches if isinstance(total_loss_l0,
torch.Tensor) else total_loss_l0 / n_batches
avg_l1 = total_loss_l1.item() / n_batches if isinstance(total_loss_l1,
torch.Tensor) else total_loss_l1 / n_batches
avg_l2 = total_loss_l2.item() / n_batches if isinstance(total_loss_l2,
torch.Tensor) else total_loss_l2 / n_batches
avg_ent = total_entropy.item() / n_batches if isinstance(total_entropy,
torch.Tensor) else total_entropy / n_batches
avg_sc_mean = sal_c_mean_sum.item() / n_batches if isinstance(sal_c_mean_sum,
torch.Tensor) else sal_c_mean_sum / n_batches
avg_sc_std = sal_c_std_sum.item() / n_batches if isinstance(sal_c_std_sum,
torch.Tensor) else sal_c_std_sum / n_batches
avg_sm_mean = sal_m_mean_sum.item() / n_batches if isinstance(sal_m_mean_sum,
torch.Tensor) else sal_m_mean_sum / n_batches
avg_sm_std = sal_m_std_sum.item() / n_batches if isinstance(sal_m_std_sum,
torch.Tensor) else sal_m_std_sum / n_batches
lr = optimizer.param_groups[0]['lr']
epoch_time = _time.time() - epoch_start
if is_master:
with open(C.log_path, 'a', newline='') as f:
csv.writer(f).writerow([epoch, f'{lr:.2e}', f'{avg_loss:.4f}', f'{avg_l0:.4f}',
f'{avg_l1:.4f}', f'{avg_l2:.4f}', f'{avg_ent:.4f}',
f'{avg_sc_mean:.4f}', f'{avg_sc_std:.4f}', f'{avg_sm_mean:.4f}',
f'{avg_sm_std:.4f}',
f'{acc:.2f}', f'{best_acc:.2f}', f'{epoch_time:.1f}'])
if epoch % 5 == 0 or epoch <= 5:
print(
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})")
generate_live_plots(C.log_path)
try:
inputs_vis = inputs[0:1]
_, _, (tk_c, tk_m) = ema.module.forward_eval(inputs_vis, visualize=True)
plot_patch_selection(inputs_vis[0], tk_c, tk_m, epoch, C)
except Exception as e:
pass
# Save epoch checkpoint
if hasattr(C, 'checkpoint_path'):
torch.save({
'epoch': epoch,
'model': getattr(model, '_orig_mod', model).state_dict(),
'ema': ema.state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler.state_dict(),
'best_acc': best_acc,
'run_hparams': {'max_lr': C.max_lr, 'warmup_epochs': C.warmup_epochs, 'epochs': C.epochs},
}, C.checkpoint_path)
if is_master:
print("\n Training Complete. Final Best Acc:", best_acc)
if os.path.exists(C.save_path):
final = FoViT(C).to(device)
load_matched_state_dict(final, C.save_path, device=device)
else:
final = getattr(ema.module, '_orig_mod', ema.module)
best_sweep_acc, sweep_dict, sweep_results = evaluate_confidence_sweep(
final, test_loader, C, nvml_handle=nvml_handle, is_master=is_master
)
if return_dict is not None and is_master:
return_dict['best_sweep_acc'] = best_sweep_acc
return_dict['sweep_dict'] = sweep_dict
return best_sweep_acc, sweep_dict, sweep_results
def evaluate_confidence_sweep(model, test_loader, config, thresholds=None, nvml_handle=None, is_master=True):
"""
Evaluates FoViT model across multiple adaptive early-exit confidence thresholds.
Returns (best_sweep_acc, sweep_results_dict, sweep_results_list)
"""
if thresholds is None:
thresholds = [0.50, 0.60, 0.70, 0.80, 0.85, 0.90, 0.95, 0.98, 0.99, 1.00]
device = config.device
dtype = torch.bfloat16 if device.type != 'mps' else torch.float32
if is_master:
print("\n" + "=" * 65)
print(" FoViT Adaptive Inference: Confidence Score Sweep")
print("=" * 65)
print(f" {'Threshold':>10} {'Accuracy':>10} {'Avg Loops':>12} {'Energy (J)':>10} {'TFLOPs':>10}")
best_sweep_acc = 0.0
sweep_dict = {}
sweep_results = []
heatmap_c = np.zeros(config.img_size // 16 * config.img_size // 16)
heatmap_m = np.zeros(config.img_size // 8 * config.img_size // 8)
model.eval()
with torch.no_grad():
for thresh in thresholds:
correct = 0
total = 0
sum_loops = 0.0
total_flops = 0.0
start_energy = get_energy(nvml_handle)
exit_counts = {1: 0, 2: 0, 3: 0}
with torch.autocast(device_type=device.type, dtype=dtype):
for inputs, targets in tqdm(test_loader, desc=f"Sweep T={thresh:.2f}", leave=False):
inputs, targets = inputs.to(device, non_blocking=True), targets.to(device, non_blocking=True)
logits, loops_batch, b_flops = model.forward_eval(inputs, exit_conf=thresh)
b_correct = logits.argmax(1).eq(targets).sum()
b_total = torch.tensor(targets.size(0), device=device)
if isinstance(loops_batch, torch.Tensor):
b_sum_loops = loops_batch.sum()
exit_counts[1] += (loops_batch == 1.0).sum().item()
exit_counts[2] += (loops_batch == 2.0).sum().item()
exit_counts[3] += (loops_batch == 3.0).sum().item()
else:
b_sum_loops = torch.tensor(loops_batch * targets.size(0), device=device)
exit_counts[3] += targets.size(0)
b_flops_tensor = torch.tensor(b_flops, device=device)
total += b_total
correct += b_correct
sum_loops += b_sum_loops
total_flops += b_flops_tensor
if thresh >= 0.99:
try:
_, _, (tk_c, tk_m) = model.forward_eval(inputs[0:1], exit_conf=1.0, visualize=True)
for idx in tk_c: heatmap_c[idx] += 1
for idx in tk_m: heatmap_m[idx] += 1
except Exception:
pass
end_energy = get_energy(nvml_handle)
energy_j = end_energy - start_energy
tflops = (total_flops.item() if isinstance(total_flops, torch.Tensor) else total_flops) / 1e12
tot_val = total.item() if isinstance(total, torch.Tensor) else total
corr_val = correct.item() if isinstance(correct, torch.Tensor) else correct
sum_loops_val = sum_loops.item() if isinstance(sum_loops, torch.Tensor) else sum_loops
acc = 100. * corr_val / tot_val if tot_val > 0 else 0
avg_loops = sum_loops_val / tot_val if tot_val > 0 else 3.0
sweep_dict[thresh] = acc
if acc > best_sweep_acc:
best_sweep_acc = acc
if is_master:
print(f" {thresh:>10.2f} {acc:>9.2f}% {avg_loops:>11.2f} {energy_j:>10.2f} {tflops:>10.4f}")
sweep_results.append({
'threshold': thresh, 'accuracy': acc, 'avg_loops': avg_loops,
'tflops': tflops, 'exits': exit_counts
})
if is_master:
try:
plot_adaptive_inference_sweep(sweep_results)
plot_spatial_bias_heatmap(heatmap_c, heatmap_m, config)
except Exception:
pass
return best_sweep_acc, sweep_dict, sweep_results
def plot_adaptive_inference_sweep(sweep_results):
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'axes.edgecolor': '#333333',
'axes.linewidth': 2.0,
'text.color': '#212529',
'axes.labelcolor': '#212529',
'figure.dpi': 300,
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
})
# 1. Pareto Curve (Accuracy vs TFLOPs)
plt.figure(figsize=(10, 6))
tflops = [r['tflops'] for r in sweep_results]
accs = [r['accuracy'] for r in sweep_results]
labels = [f"T>{r['threshold']:.2f}" for r in sweep_results]
plt.plot(tflops, accs, marker='o', markersize=10, linewidth=2.5, color='#2CA02C', mfc='#FF7F0E')
for i, label in enumerate(labels):
plt.annotate(label, (tflops[i], accs[i]), textcoords="offset points", xytext=(0, 10), ha='center', fontsize=10,
fontweight='bold')
plt.xlabel('Compute Cost (TFLOPs)', fontweight='bold')
plt.ylabel('Evaluation Accuracy (%)', fontweight='bold')
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.savefig("adaptive_inference_pareto.pdf", bbox_inches='tight', facecolor='white')
plt.close()
# 2. Exit Distribution Histogram
plt.figure(figsize=(10, 6))
x = np.arange(len(sweep_results))
l1 = np.array([r['exits'][1] for r in sweep_results])
l2 = np.array([r['exits'][2] for r in sweep_results])
l3 = np.array([r['exits'][3] for r in sweep_results])
total = l1 + l2 + l3
total[total == 0] = 1 # prevent div zero
p1 = l1 / total * 100
p2 = l2 / total * 100
p3 = l3 / total * 100
width = 0.6
plt.bar(x, p1, width, label='Loop 0 (Coarse)', color='#ff6b6b', alpha=0.9)
plt.bar(x, p2, width, bottom=p1, label='Loop 1 (Medium)', color='#4dabf7', alpha=0.9)
plt.bar(x, p3, width, bottom=p1 + p2, label='Loop 2 (Fine)', color='#51cf66', alpha=0.9)
plt.xticks(x, [f"T={r['threshold']:.2f}" for r in sweep_results], fontweight='bold')
plt.ylabel('Exit Percentage (%)', fontweight='bold')
plt.legend(loc='upper right', frameon=True, facecolor='white')
plt.tight_layout()
plt.savefig("exit_distribution.pdf", bbox_inches='tight', facecolor='white')
plt.close()
def plot_spatial_bias_heatmap(heatmap_c, heatmap_m, config):
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'axes.edgecolor': '#333333',
'axes.linewidth': 2.0,
'text.color': '#212529',
'axes.labelcolor': '#212529',
'figure.dpi': 300,
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
})
grid_w_c = config.img_size // 16
grid_w_m = config.img_size // 8
hm_c = heatmap_c.reshape(grid_w_c, grid_w_c)
hm_m = heatmap_m.reshape(grid_w_m, grid_w_m)
fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor='white')
sns.heatmap(hm_c, cmap='Reds', ax=axes[0], cbar_kws={'label': 'Selection Frequency'})
axes[0].set_xlabel('Spatial X', fontweight='bold')
axes[0].set_ylabel('Spatial Y', fontweight='bold')
sns.heatmap(hm_m, cmap='Blues', ax=axes[1], cbar_kws={'label': 'Selection Frequency'})
axes[1].set_xlabel('Spatial X', fontweight='bold')
axes[1].set_ylabel('Spatial Y', fontweight='bold')
plt.tight_layout()
plt.savefig("spatial_bias_heatmap.pdf", bbox_inches='tight', facecolor='white')
plt.close()
def plot_patch_selection(img_tensor, topk_c, topk_m, epoch, config):
import numpy as np
import matplotlib.patches as patches
from matplotlib.lines import Line2D
try:
ds = config.dataset.lower()
# Use ImageNet stats for VTAB or unknown datasets (matches training normalization)
if ds.startswith('vtab') or ds not in DataFactory.STATS:
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1).to(img_tensor.device)
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1).to(img_tensor.device)
else:
stats = DataFactory.STATS[ds]
mean = torch.tensor(stats[0]).view(3, 1, 1).to(img_tensor.device)
std = torch.tensor(stats[1]).view(3, 1, 1).to(img_tensor.device)
img = img_tensor * std + mean
img = img.clamp(0, 1).cpu().permute(1, 2, 0).numpy()
H, W = config.img_size, config.img_size
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'axes.edgecolor': '#333333',
'axes.linewidth': 2.0,
'text.color': '#212529',
'axes.labelcolor': '#212529',
'figure.dpi': 300,
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
})
fig, ax = plt.subplots(1, 1, figsize=(10, 10), facecolor='white')
ax.imshow(img)
ax.axis('off')
grid_w = W // 16
patch_dim_c = 16
# Color codes
color_c = np.array([1.0, 0.2, 0.2]) # Red for coarse->medium
color_m = np.array([0.2, 0.5, 1.0]) # Blue for medium->fine
# Create alpha blended overlay
overlay = np.zeros_like(img, dtype=np.float32)
alpha_mask = np.zeros((H, W), dtype=np.float32)
for idx in topk_c:
r, c = idx // grid_w, idx % grid_w
y, x = r * patch_dim_c, c * patch_dim_c
overlay[y:y + patch_dim_c, x:x + patch_dim_c] = color_c
alpha_mask[y:y + patch_dim_c, x:x + patch_dim_c] = 0.35
rect = patches.Rectangle((x, y), patch_dim_c, patch_dim_c, linewidth=1.5, edgecolor='#ff3333',
facecolor='none', alpha=0.8)
ax.add_patch(rect)
grid_mw = W // 8
patch_dim_m = 8
for idx in topk_m:
r, c = idx // grid_mw, idx % grid_mw
y, x = r * patch_dim_m, c * patch_dim_m
overlay[y:y + patch_dim_m, x:x + patch_dim_m] = color_m
alpha_mask[y:y + patch_dim_m, x:x + patch_dim_m] = 0.45
rect = patches.Rectangle((x, y), patch_dim_m, patch_dim_m, linewidth=1.5, edgecolor='#3366ff',
facecolor='none', alpha=0.9)
ax.add_patch(rect)
alpha_mask = np.expand_dims(alpha_mask, axis=-1)
blended = img * (1 - alpha_mask) + overlay * alpha_mask
ax.imshow(blended)
legend_elements = [
Line2D([0], [0], marker='s', color='w', label='Coarse to Medium',
markerfacecolor='#ff3333', markersize=15, alpha=0.7, markeredgewidth=2, markeredgecolor='#ff3333'),
Line2D([0], [0], marker='s', color='w', label='Medium to Fine',
markerfacecolor='#3366ff', markersize=15, alpha=0.8, markeredgewidth=2, markeredgecolor='#3366ff')
]
ax.legend(handles=legend_elements, loc='upper right', frameon=True, facecolor='white', framealpha=0.95,
fontsize=16, edgecolor='#333333', borderpad=0.8)
plt.tight_layout()
plt.savefig(f"patch_selection_epoch_{epoch:03d}.pdf", bbox_inches='tight', dpi=300, facecolor='white',
edgecolor='none')
plt.close(fig)
except Exception as e:
print("Plotting error:", e)
if __name__ == '__main__':
cfg = Config()
train(cfg)
# %%writefile remsvit.py
##WORKING MODEL##
import math
import os
import csv
import pickle
from datetime import datetime
from functools import lru_cache
import shutil
import numpy as np
from tqdm import tqdm
try:
import pynvml
except ImportError:
pynvml = None
def _get_writable_cache_dir():
"""Returns a writable directory for caching: /kaggle/working on Kaggle, else cwd."""
kaggle_working = '/kaggle/working'
if os.path.isdir(kaggle_working) and os.access(kaggle_working, os.W_OK):
return kaggle_working
return os.getcwd()
import torch
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
if hasattr(torch, 'set_float32_matmul_precision'):
torch.set_float32_matmul_precision('high')
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.optim.swa_utils import AveragedModel
from torchvision.transforms import v2
import torchvision
import torchvision.transforms as transforms
import os
import shutil
import urllib.request
import subprocess
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import random
def set_seed(seed: int = 42):
"""Make runs deterministic for reproducibility (CVPR requirement)."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Note: deterministic=True and benchmark=False can slow down training.
# We leave benchmark=True here by default as ImageNet needs speed,
# but the seeds alone eliminate 99% of the variance from stochastic ops.
os.environ['PYTHONHASHSEED'] = str(seed)
class Config:
seed = 1992 # For reproducible runs
# Dataset
# For imagenet1k/imagenet100: set data_dir to the PARENT folder that contains
# imagenet_part_1/, imagenet_part_2/, ... OR a single folder with train/ and val/ sub-dirs.
# Example: data_dir = '/kaggle/input/imagenet-object-localization-challenge'
data_dir = "/home/admin/PycharmProjects/Deepresearch/data/archive"
dataset = 'imagenet1k'
num_classes = 1000 # cifar10=10, cifar100=100, imagenet1k=1000, imagenet100=100, tiny_imagenet=200
img_size = 224 # use 224 for imagenet1k/imagenet100
in_channels = 3
num_workers = 16 # WARNING: ImageNet-1K requires AT LEAST 16 workers, otherwise JPEG decoding caps out at ~120 img/s
prefetch_factor = 2
# Architecture
dim = 320
num_heads = 4 # 8 heads × 40 head_dim
depth = 4 # Shared blocks × 3 loops = 12 effective layers
mlp_ratio = 3.0
dropout = 0.1 # Increased for larger capacity
lrmin = 1e-5
# Recurrent Saliency (Pareto-optimal inference defaults)
k1_ratio = 0.35 # % of coarse patches to refine into medium
k2_ratio = 0.45 # % of medium patches to refine into fine
# Training
batch_size = 16 # Reduced from 128 to prevent VRAM swapping
accum_iter = 2 # Gradient accumulation steps
epochs = 50
accelerator = 'gpu' # Options: 'gpu' or 'tpu'
max_lr = 1e-4 # Scaled for smaller batch size
weight_decay = 0.1 # Reduced from 0.2: 0.05 is standard for tiny/small ViTs on ImageNet
label_smoothing = 0.1
ema_decay = 0.9999
grad_clip = 1.0