# eleutherai/sparsify architecture

> Architecture diagram of the GitHub repository eleutherai/sparsify, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-06-05). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/eleutherai/sparsify
- Repository: https://github.com/eleutherai/sparsify

## Overview

##### Project type and purpose
- This is an open-source Python library and CLI tool (“sparsify”) for training and using _k_-sparse autoencoders (SAEs) on the activations of HuggingFace language models. It provides:
- A command-line interface (`python -m sparsify …`)
- A programmatic API
- Support for on-the-fly activation computation, training, fine-tuning, and distributed training

##### File structure
- Top-level:
- `.github/workflows` – CI build
- `pyproject.toml` – packaging, dependencies
- `README.md`, `CHANGELOG.md`, `LICENSE`
- `sparsify/` core package:
- `__main__.py` – CLI entrypoint
- `config.py` – `TrainConfig`, `SaeConfig` definitions
- `data.py` – dataset loading & chunk_and_tokenize
- `trainer.py` – `Trainer` class, training loop
- `sparse_coder.py`, `fused_encoder.py`, `sign_sgd.py`, `muon.py`, `xformers.py` – SAE internals, optimizers, fused ops
- `utils.py` – helpers
- `tests/` – unit tests for encode/decode

##### README for additional insights
- Describes:
- Loading pretrained SAEs from the HuggingFace Hub
- Training via CLI or programmatic API
- Distributed training with PyTorch DDP or module sharding
- Custom hookpoints, activation functions, k-decay, end-to-end training

##### Main components
a. CLI layer
- `sparsify.__main__` – parses arguments, loads `TrainConfig`
b. Configuration
- `config.py` – holds hyperparameters (hookpoints, k, batch_size, lr, etc.)
c. Data Pipeline
- `data.py` – `load_dataset` (HuggingFace Datasets)
- `chunk_and_tokenize` → token batches
d. Model Layer
- HuggingFace Transformers model & tokenizer
- External service: HuggingFace Hub (model weights + datasets)
e. SAE Modules
- For each hookpoint, a small autoencoder:
– `sparse_coder.py` (encoder/decoder)
– `fused_encoder.py` (optimized top-k operator)
– optional accelerated paths in `muon.py`, `xformers.py`
f. Trainer Engine
- `trainer.py`
- Batches go: Model → hidden activations → flatten → SAE.encode
- Loss computation, SignSGD optimizer (`sign_sgd.py`)
- Backprop, weight update, gradient accumulation
- Optional distributed training:
– DDP replication or `--distribute_modules` sharding across GPUs
g. Output & Persistence
- Checkpointing SAEs to disk and/or pushing to HuggingFace Hub via `Sae.save_to_hub`

##### Relationships & interactions
- CLI → Config → Trainer
- Trainer pulls Data Pipeline & Model & Tokenizer → produces activation tensors
- Activations → SAE modules → latent codes → decoder → reconstruction
- Trainer uses Optimizer to update SAE parameters
- Optional hooks for fine-tuning (`--finetune`)
- Distributed training: communicator layer between Trainer replicas

##### Architectural patterns & design principles
- Modular: clear separation between data, model, SAE, training
- Thin CLI layer on top of a reusable API
- Pluggable hookpoints via Unix glob patterns
- On-the-fly compute over caching trade-off
- Use of PyTorch’s DDP or manual module distribution

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% User Interface Layer
    subgraph "User Interface"
        CLI["Sparsify CLI"]:::frontend
        API["Programmatic API"]:::frontend
    end

    %% Configuration
    Config["TrainConfig & SaeConfig"]:::frontend

    %% Training Engine
    Trainer["Trainer Engine\n(DDP / Module Sharding)"]:::frontend

    %% Data Pipeline
    DataLoader["Dataset Loading"]:::data
    Tokenizer["Chunk & Tokenize"]:::data

    %% Model & Activation
    Model["HF Transformers Model & Tokenizer"]:::compute
    Activations["Extract Activations"]:::compute

    %% SAE Modules
    subgraph "SAE Modules"
        SC["Sparse Coder"]:::compute
        FE["Fused Encoder"]:::compute
        MU["MuOn Accelerated Path"]:::compute
        XF["xFormers Integration"]:::compute
    end

    SAE["SAE Encoder/Decoder Pool"]:::compute
    Latent["Latent Codes"]:::compute
    Decoder["SAE Decoder"]:::compute
    Recon["Reconstruction"]:::compute
    Loss["Loss Computation"]:::compute
    Optimizer["SignSGD Optimizer"]:::compute

    %% Utilities & Persistence
    Utils["Utility Helpers"]:::frontend
    Checkpoint["Checkpointing"]:::external
    Hub["HuggingFace Hub"]:::external

    %% Dev Infrastructure
    subgraph "Dev Infrastructure"
        CI["CI Workflow"]:::infra
        PKG["pyproject.toml"]:::infra
        TEST1["tests/test_encode.py"]:::infra
        TEST2["tests/test_decode.py"]:::infra
    end

    %% Connections
    CLI --> Config
    API --> Config
    Config --> Trainer

    Trainer --> DataLoader
    DataLoader --> Tokenizer
    Tokenizer --> Model
    Model --> Activations
    Activations --> SAE
    SC --> SAE
    FE --> SAE
    MU --> SAE
    XF --> SAE
    SAE --> Latent
    Latent --> Decoder
    Decoder --> Recon
    Recon --> Loss
    Loss --> Optimizer
    Optimizer --> Trainer

    Trainer --> Utils
    Utils --> Checkpoint
    Checkpoint --> Hub

    %% Click Events
    click CLI "https://github.com/eleutherai/sparsify/blob/main/sparsify/__main__.py"
    click API "https://github.com/eleutherai/sparsify/blob/main/sparsify/__init__.py"
    click Config "https://github.com/eleutherai/sparsify/blob/main/sparsify/config.py"
    click Trainer "https://github.com/eleutherai/sparsify/blob/main/sparsify/trainer.py"
    click DataLoader "https://github.com/eleutherai/sparsify/blob/main/sparsify/data.py"
    click SC "https://github.com/eleutherai/sparsify/blob/main/sparsify/sparse_coder.py"
    click FE "https://github.com/eleutherai/sparsify/blob/main/sparsify/fused_encoder.py"
    click MU "https://github.com/eleutherai/sparsify/blob/main/sparsify/muon.py"
    click XF "https://github.com/eleutherai/sparsify/blob/main/sparsify/xformers.py"
    click Optimizer "https://github.com/eleutherai/sparsify/blob/main/sparsify/sign_sgd.py"
    click Utils "https://github.com/eleutherai/sparsify/blob/main/sparsify/utils.py"
    click CI "https://github.com/eleutherai/sparsify/blob/main/.github/workflows/build.yml"
    click PKG "https://github.com/eleutherai/sparsify/blob/main/pyproject.toml"
    click TEST1 "https://github.com/eleutherai/sparsify/blob/main/tests/test_encode.py"
    click TEST2 "https://github.com/eleutherai/sparsify/blob/main/tests/test_decode.py"

    %% Styles
    classDef frontend fill:#D0E8FF,stroke:#0066CC,color:#003366
    classDef data fill:#E0FFE0,stroke:#00AA00,color:#006600
    classDef compute fill:#FFE0B2,stroke:#FF8C00,color:#B35000
    classDef external fill:#F0F0F0,stroke:#AAAAAA,color:#555555
    classDef infra fill:#F2E0FF,stroke:#AA00AA,color:#660066
```
