fovit / README.md
deeplumiere's picture
Update README.md
8542b56 verified
|
Raw History Blame Contribute Delete
6.9 kB
metadata
license: mit
datasets:
  - ILSVRC/imagenet-1k
tags:
  - vision
  - image-classification
  - vision-transformer
  - vit
  - foveated-attention
  - dynamic-inference
  - early-exit
  - green-ai
  - pytorch
library_name: pytorch
pipeline_tag: image-classification

FoViT: Foveated Vision Transformer

πŸ“Œ Model Overview

FoViT (Foveated Vision Transformer) (also referenced as RemSViT) is an efficient, biologically inspired Vision Transformer architecture that mimics the foveation and saccadic mechanism of the human visual system.

Standard Vision Transformers uniformly compute self-attention across all spatial patches at a single high resolution, incurring severe quadratic computational overhead on uninformative background patches. In contrast, FoViT executes recurrent, multi-scale hierarchical examination:

  1. Coarse Peripheral Glance (Loop 0): Rapidly scans the entire visual field at low spatial resolution ($16 \times 16$ coarse tokens) to establish global context and predict a spatial saliency map.
  2. Intermediate Saccadic Inspection (Loop 1): Selectively queries the top-$K_1$ most salient coarse regions, unpacking them into medium-resolution ($8 \times 8$) foveal tokens while retaining unselected coarse tokens for peripheral context.
  3. Fine Foveal Scrutiny (Loop 2): Narrows focus onto the top-$K_2$ medium regions, unpacking them into high-resolution ($4 \times 4$) fine foveal patches for fine-grained classification.
  4. Adaptive Early-Exit Inference: Dynamically terminates computation after Loop 0 or Loop 1 when classification prediction confidence reaches or exceeds an adaptive threshold ($\tau_{\text{exit}}$), yielding dramatic latency and energy savings on easy inputs while allocating full compute only to difficult samples.

Key Innovations

  • Weight-Shared Recurrent Backbone: Features 4 shared transformer blocks executed across 3 loops, matching the representational depth of a 12-layer ViT at ~1/3 of the parameter count.
  • LoopAdjuster Adapters: Compact bottleneck adapters ($r=16$) modulate Multi-Head Self-Attention and MLP projections per loop index without bloating parameter count.
  • FiLM Feature Modulation: Coarse saliency representations modulate finer tokens via affine scaling and shifting ($\gamma, \beta$), ensuring smooth cross-scale feature propagation.
  • 2D Rotary Position Embeddings (2D RoPE): Implements continuous, scale-invariant spatial coordinates across dynamic multiscale resolutions ($14\times 14 \rightarrow 28\times 28 \rightarrow 56\times 56$).
  • Differentiable Top-K (STE): Uses a Straight-Through Estimator with Gumbel-Softmax perturbations during training to backpropagate gradients through discrete patch routing.
  • CLS-to-Patch Gated Broadcast: Broadcasts updated global semantics from [CLS] back into patch representations across iterations.

πŸ“Š Computational Profile & Efficiency

Inference Stage Active Loops Average GMACs Top-1 Accuracy Description
Stage 1 (Loop 0 Exit) 1 ~2.70 GMACs High (Rapid) Peripheral coarse classification for easy samples
Stage 2 (Loop 1 Exit) 2 ~5.52 GMACs Very High Saccadic zoom with medium resolution focus
Full Pass (Loop 2) 3 ~14.42 GMACs Best Deep fine-scale foveal resolution
Adaptive Inference Variable (1–3) Dynamic Pareto-Optimal Tune $\tau_{\text{exit}} \in [0.5, 1.0]$ at runtime without retraining

Profiling carried out using fvcore.nn.FlopCountAnalysis on $224 \times 224$ images (1 MAC = 1 FLOP).


πŸ› οΈ Getting Started / Quickstart

1. Model Instantiation & Adaptive Inference

import torch
from fovit import FoViT, Config

# Initialize configuration and model
config = Config()
config.num_classes = 1000
config.img_size = 224

model = FoViT(config)
model.eval()

# Dummy input batch (Batch Size = 2, 3 Channels, 224x224)
images = torch.randn(2, 3, 224, 224)

# Adaptive early-exit inference (exit confidence threshold = 0.90)
with torch.no_grad():
    logits, loops_executed, _ = model.forward_eval(images, exit_conf=0.90)

print(f"Logits shape: {logits.shape}")
print(f"Loops executed per sample: {loops_executed.tolist()}")

2. Extracting Saliency & Foveated Patch Indices

with torch.no_grad():
    logits, _, (topk_coarse, topk_medium) = model.forward_eval(images[0:1], visualize=True)

print(f"Selected coarse patch indices: {topk_coarse}")
print(f"Selected medium patch indices: {topk_medium}")

πŸ‹οΈ Training Recipe & Optimization Details

The training pipeline uses multi-exit supervision with self-distillation and entropy regularization:

Ltotal=LCE(y2,y)+w1Ldistill(y1,y2)+w0Ldistill(y0,y2)+Ξ»entH(S) \mathcal{L}_{\text{total}} = \mathcal{L}_{\text{CE}}(y_2, y) + w_1 \mathcal{L}_{\text{distill}}(y_1, y_2) + w_0 \mathcal{L}_{\text{distill}}(y_0, y_2) + \lambda_{\text{ent}} \mathcal{H}(\mathcal{S})

  • Self-Distillation: Soft probability distributions from Loop 2 guide earlier exits with temperature annealing ($T_{\text{dist}} \in [2.0, 4.0]$).
  • Optimizer: AdamW ($\text{LR} = 1\times 10^{-4}$, $\text{weight decay} = 0.1$, $\beta_1 = 0.9, \beta_2 = 0.999$, gradient clip $= 1.0$).
  • LR Schedule: 5 epochs linear warmup followed by Cosine Annealing decay down to $1\times 10^{-5}$.
  • Data Augmentation: MixUp ($\alpha = 0.5$), CutMix ($\alpha = 0.5$), RandAugment (2 ops, magnitude 9), ColorJitter, RandomErasing ($p = 0.25$).
  • Regularization: Label Smoothing ($0.1$), DropPath ($0.1$), SWA / EMA (decay = 0.9999).
  • Gumbel $\tau$ Annealing: Starts soft at $\tau = 1.0$ and linearly anneals to $\tau = 0.1$.

πŸ“¦ Hyperparameter Configuration

class Config:
    img_size = 224
    in_channels = 3
    num_classes = 1000

    # Architecture Dimension
    dim = 320               # Transformer embedding dimension
    num_heads = 4           # 4 heads x 80 head_dim
    depth = 4               # 4 shared blocks x 3 loops = 12 effective layers
    mlp_ratio = 3.0         # MLP expansion ratio
    dropout = 0.1

    # Saliency Ratios
    k1_ratio = 0.35         # Refines top 35% coarse patches into medium (4x)
    k2_ratio = 0.45         # Refines top 45% medium patches into fine (4x)

🌿 Green AI & Energy Tracking

FoViT integrates native NVML GPU power sampling:

  • Eliminates computation on background regions (sky, uniform surfaces, repetitive noise).
  • Delivers up to 60–70% average inference energy reduction via adaptive early-exit without degradation in top-1 accuracy.

πŸ“¬ Contact & Collaboration

This is an ongoing research project (Work in Progress). Suggestions, collaborations, and discussions are welcome!