How hchautran/sparsesam works
1. Repository purpose
- This repo is a research/benchmarking framework for accelerating transformer-based vision models, mainly SAM-HQ and Perception Encoder (PE), using training-free activation sparsification and token reduction methods.
- The central design choice is runtime patching: algorithms are applied to an already-loaded model, run for evaluation, then removed without changing the checkpoint.
2. Core architecture boundary: algos/
- algos/ contains the actual algorithm implementations and the integration layer that patches model internals.
- It is organized by algorithm family: sparsesam, tome, gradtome, sparge, piecewise, plus shared kernel and base abstractions.
- This directory is the main boundary between “baseline model code” and “compressed execution”.
3. Unified algorithm registry
- algos/registry.py is the key orchestration point.
- It exposes apply_sam, remove_all_sam, apply_pe, and remove_all_pe, so tasks do not need algorithm-specific wiring.
- This registry lets the same eval/profile scripts sweep many (algorithm, ratio) combinations uniformly.
4. SAM-side algorithm families
- algos/sparsesam/, algos/tome/, algos/gradtome/, algos/sparge/, and algos/piecewise/ contain variants for patching SAM(-HQ) image encoders and sometimes predictors.
- SparseSAM combines structured sparse attention with residual-consistency MLP behavior.
- ToMe/GradToMe are token-merging baselines; SpargeAttn and Piecewise are sparse-attention baselines; these are used as comparative methods and integration references.
5. PE-side algorithm families
- algos/pe_base/ defines shared abstractions for Perception Encoder patching.
- algos/gradtome/, algos/sparsesam/, algos/tome/, and algos/sparge/ each include PE-compatible variants such as pe_compress.py and pe_partial.py.
- The PE path supports both stage-compression and partial-token-count style patches, which matters because PE evaluation is centered on zero-shot classification and throughput.
6. Vendored upstream model code
- algos/3rd_party/ contains external model implementations brought into the repo as submodules or vendored sources.
- Important dependencies here are SAM-HQ, Perception Encoder, SpargeAttn, and piecewise-sparse-attention.
- This means the repo is not a standalone model implementation; it overlays new sparsification behavior onto upstream backbones and kernels.
7. Kernel and low-level acceleration layer
- algos/kernels/flash_attn.py and algos/pe_base/cute_kernel.py indicate a low-level acceleration layer for attention kernels.
- These are relevant for performance-sensitive paths such as FlashAttention-based attention, rel-pos/RoPE fusion, and custom CUDA/Cutlass-style kernels.
- The repository therefore has a two-level structure: high-level patching logic plus optional fused kernel support.
8. Evaluation entry points live under tasks/
- tasks/ is split by benchmark track: sam_hq44k, sam_coco, sam_profile, sam3_profile, sam3_saco_gold, and pe_imagenet.
- Each task has Python entry points plus shell wrappers, and the wrappers are designed to be env-overridable for reproducible sweeps.
- These scripts are the operational layer that connects model loading, algorithm patching, dataset iteration, and result logging.
9. Benchmark-specific data flow
- For SAM-HQ / HQ-44K, the flow is: load SAM-HQ checkpoint → patch model.image_encoder → run segmentation inference → compute mIoU/Boundary IoU/latency/memory.
- For COCO box-prompted segmentation, the flow is: detector produces boxes via MMDetection configs → SAM-HQ predictor uses those boxes → apply patch to the injected predictor/backbone → evaluate segmentation quality.
- For PE ImageNet, the flow is: load PE visual backbone → patch model.visual → run zero-shot classification → report top-1/top-5 plus performance metrics.
10. Task-specific external dependencies
- tasks/sam_coco/configs/ contains MMDetection-style configs for detectors such as DINO, H-DETR, and YOLOX.
- This is the main place where the repo depends on an external detection stack, because COCO evaluation uses detector-generated prompts rather than ground-truth-only model inputs.
- That makes the COCO path architecturally distinct from the pure image-encoder benchmarks.
11. Shared utilities
- utils/ holds common support code for data loading, SAM precision handling, visualization, and benchmark utilities.
- These helpers reduce duplication across tasks and centralize data-format conversions and evaluation bookkeeping.
- utils/coco_mmdet/ is a small bridge package for the COCO/MMDetection flow.
12. Experiment artifacts and outputs
- benchmark_results/, sam3_logs/, and task-local RESULTS.md files capture benchmark outputs and reproduced numbers.
- ckts/ and data/ are expected runtime inputs: checkpoints and benchmark datasets.
- notebooks/ and input_imgs/ support interactive exploration and demos rather than the main evaluation pipeline.
13. Docs as the integration contract
- docs/ADDING_ALGORITHMS.md, docs/ADDING_SAM.md, and docs/ADDING_PE.md define the repository’s extension model.
- The key architectural rule is: add a new patch implementation under algos/, register it, and it automatically becomes available to all task scripts.
- This makes the registry the primary extension boundary for the whole repo.
14. What an architecture diagram should emphasize
- Draw one central “algorithm registry / patching layer” between task scripts and model backbones.
- Show two main model branches: SAM-HQ and Perception Encoder.
- Show tasks/ as benchmark drivers, algos/3rd_party/ as external model sources, utils/ as shared support, and benchmark_results/RESULTS.md as outputs.
Main entry points: registry.py Registry · sam-hq SAM-HQ · perception_models Perception Encoder · eval_coco.py COCO eval
Components 20
Algorithms
Runtime patching layer and algorithm families.
- Registry · Unified entry point that applies and removes SAM/PE patches.
algos/registry.py - SparseSAM · Sparse-attention and residual-consistency variants for SAM and PE.
algos/sparsesam - ToMe · Token-merging baseline and PE-compatible patch variants.
algos/tome - GradToMe · Gradient-aware token merging for SAM and PE patching.
algos/gradtome - Sparge · Sparse-attention baseline implementations for SAM and PE.
algos/sparge - Piecewise · Piecewise sparse-attention baseline for SAM patching.
algos/piecewise - PE base · Shared abstractions and low-level helpers for Perception Encoder patching.
algos/pe_base
Tasks
Benchmark drivers and profiling entry points.
- HQ-44K eval · SAM-HQ evaluation driver for HQ-44K segmentation.
tasks/sam_hq44k/eval_hq44k.py - COCO eval · COCO box-prompted segmentation evaluation driver.
tasks/sam_coco/eval_coco.py - PE eval · Zero-shot ImageNet evaluation driver for Perception Encoder.
tasks/pe_imagenet/eval_pe_clip.py - SAM profile · Encoder and attention profiling entry point for SAM.
tasks/sam_profile/profile_encoder.py - SAM3 profile · SAM3 encoder profiling entry point.
tasks/sam3_profile/profile_encoder_sam3.py - COCO configs · MMDetection-style detector and runtime configs used for COCO prompting.
tasks/sam_coco/configs
Support
Shared utilities, kernel helpers, and evaluation glue.
- Flash kernels · Optional fused attention and kernel acceleration layer.
algos/kernels/flash_attn.py - Utils · Common data, precision, visualization, and benchmark helpers.
utils/utils.py - COCO bridge · Glue between COCO evaluation and MMDetection-style detector outputs.
utils/coco_mmdet
Vendored models
Upstream backbone and method sources brought into the repo.
- SAM-HQ · Vendored upstream SAM-HQ model implementation.
algos/3rd_party/sam-hq - Perception Encoder · Vendored upstream Perception Encoder implementation.
algos/3rd_party/perception_models
Docs
Extension and usage contracts.
- Add algorithms · Repository contract for adding and registering new patch methods.
docs/ADDING_ALGORITHMS.md
Artifacts
Captured logs and benchmark outputs.
- Run log · Representative benchmark output log artifact.
sam3_logs/baseline/gold_metaclip_nps/logs/log.txt
Connections 27
- HQ-44K eval → Registry: patches via · HQ-44K evaluation applies runtime patches through the registry.
- COCO eval → Registry: patches via · COCO evaluation uses the registry to inject and remove methods.
- PE eval → Registry: patches via · PE ImageNet evaluation routes through unified patch entry points.
- SAM profile → Registry: profiles via · Profiling scripts exercise patched and baseline SAM execution.
- SAM3 profile → Registry: profiles via · SAM3 profiling also uses the same patching boundary.
- Registry → SparseSAM: applies · Registry exposes SparseSAM variants to tasks.
- Registry → ToMe: applies · Registry exposes ToMe variants to tasks.
- Registry → GradToMe: applies · Registry exposes GradToMe variants to tasks.
- Registry → Sparge: applies · Registry exposes Sparge variants to tasks.
- Registry → Piecewise: applies · Registry exposes Piecewise variants to tasks.
- Registry → PE base: applies · PE patching is built on the shared PE abstraction layer.
- SparseSAM → SAM-HQ: patches · SparseSAM mutates SAM-HQ encoder and related blocks at runtime.
- GradToMe → SAM-HQ: patches · GradToMe variants target SAM-HQ internals.
- Sparge → SAM-HQ: patches · Sparge methods integrate with SAM-HQ backbones.
- Piecewise → SAM-HQ: patches · Piecewise sparse-attention is used as a SAM-HQ baseline.
- SparseSAM → Perception Encoder: patches · PE-compatible SparseSAM variants modify the visual backbone.
- ToMe → Perception Encoder: patches · PE-compatible ToMe variants compress the visual stream.
- GradToMe → Perception Encoder: patches · PE-compatible GradToMe variants compress stages or token counts.
- Sparge → Perception Encoder: patches · PE-compatible Sparge variants apply sparse attention.
- PE base → Flash kernels: uses · PE abstractions can delegate to fused attention/kernel helpers.
- COCO eval → COCO configs: loads · COCO evaluation consumes detector configs for box prompts.
- COCO eval → COCO bridge: bridges · COCO evaluation uses MMDetection integration utilities.
- HQ-44K eval → Utils: uses · Shared utilities handle data loading, precision, and reporting.
- PE eval → Utils: uses · PE evaluation uses common benchmark helpers.
- SAM profile → Utils: uses · Profiling scripts share common support utilities.
- Add algorithms → Registry: describes · Docs define registry-based extension flow for new algorithms.
- Run log → SAM profile: records · Representative output artifact from profiling/baseline runs.