# hchautran/sparsesam architecture

> Architecture diagram of the GitHub repository hchautran/sparsesam, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-11). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hchautran/sparsesam
- Repository: https://github.com/hchautran/sparsesam

## Overview

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: [`algos/registry.py`](https://github.com/hchautran/sparsesam/blob/main/algos/registry.py) (Registry), [`algos/3rd_party/sam-hq`](https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/sam-hq) (SAM-HQ), [`algos/3rd_party/perception_models`](https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/perception_models) (Perception Encoder), [`tasks/sam_coco/eval_coco.py`](https://github.com/hchautran/sparsesam/blob/main/tasks/sam_coco/eval_coco.py) (COCO eval)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_algos["Algorithms"]
  node_algos_registry["Registry<br/>[registry.py]"]
  node_algos_sparsesam["SparseSAM<br/>sam patches"]
  node_algos_tome["ToMe<br/>token merge"]
  node_algos_gradtome["GradToMe<br/>gradient merge"]
  node_algos_sparge["Sparge<br/>sparse attn"]
  node_algos_piecewise["Piecewise<br/>sparse attn"]
  node_algos_pe_base["PE base<br/>pe abstractions"]
end

subgraph group_tasks["Tasks"]
  node_tasks_sam_hq44k["HQ-44K eval<br/>sam benchmark<br/>[eval_hq44k.py]"]
  node_tasks_sam_coco["COCO eval<br/>sam benchmark<br/>[eval_coco.py]"]
  node_tasks_pe_imagenet["PE eval<br/>pe benchmark<br/>[eval_pe_clip.py]"]
  node_tasks_sam_profile["SAM profile<br/>profiling<br/>[profile_encoder.py]"]
  node_tasks_sam3_profile["SAM3 profile<br/>profiling"]
  node_tasks_sam_coco_configs["COCO configs<br/>detector configs"]
end

subgraph group_support["Support"]
  node_algos_kernels["Flash kernels<br/>attention kernels<br/>[flash_attn.py]"]
  node_utils_common["Utils<br/>shared support<br/>[utils.py]"]
  node_utils_coco_bridge["COCO bridge<br/>mmdet bridge"]
end

subgraph group_vendored["Vendored models"]
  node_sam_hq_src["SAM-HQ<br/>vendored backbone"]
  node_pe_src["Perception Encoder<br/>vendored backbone"]
end

subgraph group_docs["Docs"]
  node_docs_contract["Add algorithms<br/>docs"]
end

subgraph group_artifacts["Artifacts"]
  node_artifact_log["Run log<br/>artifact<br/>[log.txt]"]
end

node_tasks_sam_hq44k -->|"patches via"| node_algos_registry
node_tasks_sam_coco -->|"patches via"| node_algos_registry
node_tasks_pe_imagenet -->|"patches via"| node_algos_registry
node_tasks_sam_profile -->|"profiles via"| node_algos_registry
node_tasks_sam3_profile -->|"profiles via"| node_algos_registry
node_algos_registry -->|"applies"| node_algos_sparsesam
node_algos_registry -->|"applies"| node_algos_tome
node_algos_registry -->|"applies"| node_algos_gradtome
node_algos_registry -->|"applies"| node_algos_sparge
node_algos_registry -->|"applies"| node_algos_piecewise
node_algos_registry -->|"applies"| node_algos_pe_base
node_algos_sparsesam -->|"patches"| node_sam_hq_src
node_algos_gradtome -->|"patches"| node_sam_hq_src
node_algos_sparge -->|"patches"| node_sam_hq_src
node_algos_piecewise -->|"patches"| node_sam_hq_src
node_algos_sparsesam -->|"patches"| node_pe_src
node_algos_tome -->|"patches"| node_pe_src
node_algos_gradtome -->|"patches"| node_pe_src
node_algos_sparge -->|"patches"| node_pe_src
node_algos_pe_base -->|"uses"| node_algos_kernels
node_tasks_sam_coco -->|"loads"| node_tasks_sam_coco_configs
node_tasks_sam_coco -->|"bridges"| node_utils_coco_bridge
node_tasks_sam_hq44k -->|"uses"| node_utils_common
node_tasks_pe_imagenet -->|"uses"| node_utils_common
node_tasks_sam_profile -->|"uses"| node_utils_common
node_docs_contract -->|"describes"| node_algos_registry
node_artifact_log -->|"records"| node_tasks_sam_profile

click node_algos_registry "https://github.com/hchautran/sparsesam/blob/main/algos/registry.py"
click node_algos_sparsesam "https://github.com/hchautran/sparsesam/tree/main/algos/sparsesam"
click node_algos_tome "https://github.com/hchautran/sparsesam/tree/main/algos/tome"
click node_algos_gradtome "https://github.com/hchautran/sparsesam/tree/main/algos/gradtome"
click node_algos_sparge "https://github.com/hchautran/sparsesam/tree/main/algos/sparge"
click node_algos_piecewise "https://github.com/hchautran/sparsesam/tree/main/algos/piecewise"
click node_algos_pe_base "https://github.com/hchautran/sparsesam/tree/main/algos/pe_base"
click node_algos_kernels "https://github.com/hchautran/sparsesam/blob/main/algos/kernels/flash_attn.py"
click node_sam_hq_src "https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/sam-hq"
click node_pe_src "https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/perception_models"
click node_tasks_sam_hq44k "https://github.com/hchautran/sparsesam/blob/main/tasks/sam_hq44k/eval_hq44k.py"
click node_tasks_sam_coco "https://github.com/hchautran/sparsesam/blob/main/tasks/sam_coco/eval_coco.py"
click node_tasks_pe_imagenet "https://github.com/hchautran/sparsesam/blob/main/tasks/pe_imagenet/eval_pe_clip.py"
click node_tasks_sam_profile "https://github.com/hchautran/sparsesam/blob/main/tasks/sam_profile/profile_encoder.py"
click node_tasks_sam3_profile "https://github.com/hchautran/sparsesam/blob/main/tasks/sam3_profile/profile_encoder_sam3.py"
click node_tasks_sam_coco_configs "https://github.com/hchautran/sparsesam/tree/main/tasks/sam_coco/configs"
click node_utils_common "https://github.com/hchautran/sparsesam/blob/main/utils/utils.py"
click node_utils_coco_bridge "https://github.com/hchautran/sparsesam/tree/main/utils/coco_mmdet"
click node_docs_contract "https://github.com/hchautran/sparsesam/blob/main/docs/ADDING_ALGORITHMS.md"
click node_artifact_log "https://github.com/hchautran/sparsesam/blob/main/sam3_logs/baseline/gold_metaclip_nps/logs/log.txt"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_algos_registry,node_algos_sparsesam,node_algos_tome,node_algos_gradtome,node_algos_sparge,node_algos_piecewise,node_algos_pe_base toneBlue
class node_tasks_sam_hq44k,node_tasks_sam_coco,node_tasks_pe_imagenet,node_tasks_sam_profile,node_tasks_sam3_profile,node_tasks_sam_coco_configs toneAmber
class node_algos_kernels,node_utils_common,node_utils_coco_bridge toneMint
class node_sam_hq_src,node_pe_src toneRose
class node_docs_contract toneIndigo
class node_artifact_log toneTeal
```

## Components

### Algorithms

Runtime patching layer and algorithm families.

- [Registry](https://github.com/hchautran/sparsesam/blob/main/algos/registry.py): patch registry · Unified entry point that applies and removes SAM/PE patches. · `algos/registry.py`
- [SparseSAM](https://github.com/hchautran/sparsesam/tree/main/algos/sparsesam): sam patches · Sparse-attention and residual-consistency variants for SAM and PE. · `algos/sparsesam`
- [ToMe](https://github.com/hchautran/sparsesam/tree/main/algos/tome): token merge · Token-merging baseline and PE-compatible patch variants. · `algos/tome`
- [GradToMe](https://github.com/hchautran/sparsesam/tree/main/algos/gradtome): gradient merge · Gradient-aware token merging for SAM and PE patching. · `algos/gradtome`
- [Sparge](https://github.com/hchautran/sparsesam/tree/main/algos/sparge): sparse attn · Sparse-attention baseline implementations for SAM and PE. · `algos/sparge`
- [Piecewise](https://github.com/hchautran/sparsesam/tree/main/algos/piecewise): sparse attn · Piecewise sparse-attention baseline for SAM patching. · `algos/piecewise`
- [PE base](https://github.com/hchautran/sparsesam/tree/main/algos/pe_base): pe abstractions · Shared abstractions and low-level helpers for Perception Encoder patching. · `algos/pe_base`

### Tasks

Benchmark drivers and profiling entry points.

- [HQ-44K eval](https://github.com/hchautran/sparsesam/blob/main/tasks/sam_hq44k/eval_hq44k.py): sam benchmark · SAM-HQ evaluation driver for HQ-44K segmentation. · `tasks/sam_hq44k/eval_hq44k.py`
- [COCO eval](https://github.com/hchautran/sparsesam/blob/main/tasks/sam_coco/eval_coco.py): sam benchmark · COCO box-prompted segmentation evaluation driver. · `tasks/sam_coco/eval_coco.py`
- [PE eval](https://github.com/hchautran/sparsesam/blob/main/tasks/pe_imagenet/eval_pe_clip.py): pe benchmark · Zero-shot ImageNet evaluation driver for Perception Encoder. · `tasks/pe_imagenet/eval_pe_clip.py`
- [SAM profile](https://github.com/hchautran/sparsesam/blob/main/tasks/sam_profile/profile_encoder.py): profiling · Encoder and attention profiling entry point for SAM. · `tasks/sam_profile/profile_encoder.py`
- [SAM3 profile](https://github.com/hchautran/sparsesam/blob/main/tasks/sam3_profile/profile_encoder_sam3.py): profiling · SAM3 encoder profiling entry point. · `tasks/sam3_profile/profile_encoder_sam3.py`
- [COCO configs](https://github.com/hchautran/sparsesam/tree/main/tasks/sam_coco/configs): detector 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](https://github.com/hchautran/sparsesam/blob/main/algos/kernels/flash_attn.py): attention kernels · Optional fused attention and kernel acceleration layer. · `algos/kernels/flash_attn.py`
- [Utils](https://github.com/hchautran/sparsesam/blob/main/utils/utils.py): shared support · Common data, precision, visualization, and benchmark helpers. · `utils/utils.py`
- [COCO bridge](https://github.com/hchautran/sparsesam/tree/main/utils/coco_mmdet): mmdet 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](https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/sam-hq): vendored backbone · Vendored upstream SAM-HQ model implementation. · `algos/3rd_party/sam-hq`
- [Perception Encoder](https://github.com/hchautran/sparsesam/tree/main/algos/3rd_party/perception_models): vendored backbone · Vendored upstream Perception Encoder implementation. · `algos/3rd_party/perception_models`

### Docs

Extension and usage contracts.

- [Add algorithms](https://github.com/hchautran/sparsesam/blob/main/docs/ADDING_ALGORITHMS.md): docs · Repository contract for adding and registering new patch methods. · `docs/ADDING_ALGORITHMS.md`

### Artifacts

Captured logs and benchmark outputs.

- [Run log](https://github.com/hchautran/sparsesam/blob/main/sam3_logs/baseline/gold_metaclip_nps/logs/log.txt): artifact · Representative benchmark output log artifact. · `sam3_logs/baseline/gold_metaclip_nps/logs/log.txt`

## Connections

- 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.
