Skip to content
Edit this page

Train an SAE

Train an SAE on the final layer of ruri-v3 with the data it was fine-tuned on:

muscari train-sae \
  --trainer topk \
  --model cl-nagoya/ruri-v3-310m \
  --dataset cl-nagoya/ruri-v3-dataset-ft \
  --subsets auto-wiki-qa-nemotron jaquad jqara jsquad miracl mkqa mr-tydi quiz-works \
  --columns "anc=検索クエリ: " "pos=検索文書: " "neg=検索文書: " \
  --checkpoint-every 1000 \
  --out runs/ruri-v3-310m-sae

The subsets of a dataset can come under different licenses. The dataset card lists them, and what an SAE trained on them may be used for follows from that; the command above names the subsets to read.

--columns lists the dataset columns to read and the prompt the encoder expects for each. Statistics are reported per prompt, which separates queries from documents. For an encoder that takes no prompt, label the columns instead: --columns "anc:query=" "pos:document=" "neg:document=". The defaults are 65,536 latents, k = 16 and one billion tokens, the values reported on the model card of the SAE used by Shizuku. For a first look, shrink the run with --num-latents, --total-tokens and a smaller model such as cl-nagoya/ruri-v3-30m.

The same activations through SAELens:

muscari train-sae --trainer saelens --architecture topk ...

Any corpus works. A plain text file with one text per line provides the column text:

muscari train-sae \
  --trainer topk \
  --model cl-nagoya/ruri-v3-310m \
  --data-files corpus.txt \
  --columns "text=検索文書: " \
  --out runs/my-corpus-sae

Evaluate an exported SAE on other texts. Encoder settings that you omit are read from the SAE's sae_config.json:

muscari eval-sae --sae runs/ruri-v3-310m-sae --data-files other.jsonl \
  --columns "text=検索文書: "

List what each latent responds to, most frequent first. The table goes to the terminal and the full list to latents.jsonl next to the SAE:

muscari inspect-sae --sae runs/ruri-v3-310m-sae --data-files other.jsonl \
  --columns "text=検索文書: "

Rerank the candidates of a reranking dataset with the frozen encoder and the SAE, before any retrieval training. This shows whether the encoder still ranks well with the SAE in its path, and how the SAE's features rank on their own:

muscari probe-sae --sae runs/ruri-v3-310m-sae --benchmark jqara \
  --query-prompt "検索クエリ: " --document-prompt "検索文書: "

Run muscari train-sae --help for every option. An offline example that needs no download is examples/train_tiny.py.

Python API

from muscari import (
    EncoderActivationSource,
    TopKTrainer,
    TopKTrainerConfig,
    TextColumn,
    iter_texts,
    load_sae,
    repeat_texts,
    save_topk_sae,
    shuffled_batches,
)

rows = [{"query": "...", "document": "..."}]  # any iterable of mappings
columns = [
    TextColumn("query", "検索クエリ: "),
    TextColumn("document", "検索文書: "),
]

source = EncoderActivationSource.from_pretrained("cl-nagoya/ruri-v3-30m")
# Prompts as in Sentence Transformers, if you want to name them: pass
# prompts={"query": "検索クエリ: ", "document": "検索文書: "} to from_pretrained
# and then call source.encode_batch(texts, prompt_name="document").
batches = shuffled_batches(
    source.stream(repeat_texts(lambda: iter_texts(rows, columns))),
    batch_tokens=8192,
    buffer_tokens=524_288,
)

config = TopKTrainerConfig(
    num_latents=16_384,
    k=16,
    total_tokens=50_000_000,
)
trainer = TopKTrainer(config, d_in=source.d_in)
sae = trainer.fit(batches, out_dir="runs/sae")
save_topk_sae("runs/sae", sae, {"base_model": "cl-nagoya/ruri-v3-30m"})

exported = load_sae("runs/sae", device=source.device)
hidden = source.encode_batch(["名古屋の求人"], prompt="検索文書: ")  # (tokens, d_in)
features = exported.encode(hidden)  # (tokens, num_latents), k non-zero per token

The two trainers

topk saelens
Implementation this repository SAELens SAETrainer (optional extra)
Architectures Top-K Top-K, BatchTopK (exported as JumpReLU)
Auxiliary loss AuxK with configurable aux_k, normalised by the residual variance SAELens' own: d_in // 2 dead latents, not normalised
Dead latents counted in tokens counted in steps
Schedule 5% linear warmup, cosine decay to zero linear warmup, cosine decay to lr / 100
Decoder bias at the start geometric median of the first batch the same; SAELens' own default of zero with --zero-b-dec
Checkpoint and resume yes (--checkpoint-every, --resume) no
Logging JSON lines SAELens, optionally Weights & Biases

topk is this repository's own loop. Its mechanics follow Gao et al., and its default hyperparameters are the ones stated on the model card of the SAE behind mahiyama's Shizuku models. The training code of those models is not public and this project is not affiliated with them. What the card states, what it leaves open and how to run with its settings are under Differences from the sources.

A short first run

For a first run, a small model and a short budget show whether the pipeline works on your machine before committing to a long run:

muscari train-sae \
  --trainer topk \
  --model cl-nagoya/ruri-v3-30m \
  --dataset cl-nagoya/ruri-v3-dataset-ft \
  --subsets jsquad \
  --columns "anc=検索クエリ: " "pos=検索文書: " "neg=検索文書: " \
  --num-latents 8192 \
  --total-tokens 5000000 \
  --dead-after-tokens 1000000 \
  --out runs/ruri-v3-30m-sae-trial

Inside this repository's mise environment the Hugging Face Hub is switched to offline mode so that checks never download anything. There, prompt the command with mise exec -- env HF_HUB_OFFLINE=0 uv run --frozen --no-sync. Setting the variable in front of mise exec has no effect.

On an Apple M5 Pro with MPS this command took 200 seconds, including the download of the model and the dataset subset and the held-out evaluation. The numbers it produced are under Measurements.

Limitations

  • One process, one device. No multi-GPU sharding.
  • --resume restores the SAE, optimizer and dead-latent state exactly. The data stream restarts after the texts already encoded with a new shuffle seed, so the activations that were waiting in the shuffle buffer at checkpoint time are skipped.
  • Datasets are loaded in map style and shuffled by row. Streaming datasets are not supported.
  • By default activations are used as they come out of the encoder. train-sae --normalize-inputs scales each activation to unit length first, which is the second half of the preprocessing of Gao et al. (the mean over the dimensions is not subtracted) and what LightOn's SlideOn does to its token embeddings. The setting is saved in sae_config.json and applied wherever the SAE is used: evaluation, inspection, the probe and the retrieval head. It has been run on the test model only; its effect on SAE quality or retrieval has not been measured here.
  • The SAELens backend cannot resume, and its auxiliary loss is not configurable from here.