From 528f9b07166d106211c7ddaa17e085bf743a86ae Mon Sep 17 00:00:00 2001 From: "PD User (shared)" Date: Fri, 14 Aug 2026 20:12:59 +0000 Subject: [PATCH] Add parameter-decomposition research guidance Crew-Address: agent/l1mq --- CLAUDE.md | 474 +++-------------------------------------------- README.md | 7 + docs/handbook.md | 173 +++++++++++++++++ docs/skill.md | 155 ++++++++++++++++ 4 files changed, 357 insertions(+), 452 deletions(-) create mode 100644 docs/handbook.md create mode 100644 docs/skill.md diff --git a/CLAUDE.md b/CLAUDE.md index 002af591a..bc9dbc5a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,464 +1,34 @@ -# CLAUDE.md +# Repository guidance -Guidance for Claude Code agents working in this repo. Sub-CLAUDE.md files carry the -module-specific detail; see [Module pointers](#module-pointers). +Before planning, running, or interpreting a decomposition experiment, read both guides: -## Environment +- [`docs/handbook.md`](docs/handbook.md) — the science, evidence standards, failure modes, and interpretation limits. +- [`docs/skill.md`](docs/skill.md) — the repository-specific recipe for targets, objectives, sweeps, validation, and analysis. -**Always activate the venv before running Python or git:** +For other work, start with the smallest relevant source of truth: -```bash -source .venv/bin/activate -``` - -In a worktree, run `uv sync` first so the worktree has its own `.venv`. Do NOT `cd` to -the main repo — all commands (including git) run in the worktree. - -`.env` file with WandB credentials required (see `.env.example`). - -**The repo is torch-free.** All torch was deleted (trainer is JAX; torch consumers were -de-torched; the torch oracle lives at git tag `torch-oracle`). The one torch island left -is `nano_param_decomp/` — a standalone single-file VPD reference impl for paper readers, -excluded from `make type` and not imported by any package. - -**One venv.** There is a single `.venv` at the repo root, built by `make install-dev` -(`uv sync` + pre-commit). jax is a normal dependency of the `param-decomp` distribution -(CPU jax base); GPU hosts add the `[cuda]` / `[cuda13]` extra (`uv sync --extra cuda`). - -## Project overview - -PD is a research framework for sparse parameter decomposition: target-model parameters are -decomposed into a sum of components; per-datapoint **causal importance (CI)** quantifies -how much each component can be masked; multiple loss terms balance faithfulness, -reconstruction, and sparsity. - -Three experimental domains: TMS (Toy Model of Superposition), ResidualMLP, and Language -Models. The LM experiment decomposes any HuggingFace-loadable model whose target modules -are `nn.Linear`, `nn.Embedding`, or `transformers.modeling_utils.Conv1D`. - -Three research papers describe the method, in lineage order (newest first). When this -repo says "the method", it means **VPD** — or just "PD" generically. It is *not* "SPD": -SPD is the predecessor VPD builds on. - -- **VPD** — adVersarial Parameter Decomposition — [`papers/Adversarial_Parameter_Decomposition/post.md`](papers/Adversarial_Parameter_Decomposition/post.md) ("Interpreting Language Model Parameters"). The current method and framing: scales parameter decomposition to full language models and replaces SPD's *stochastic* ablation sampling with *adversarially-chosen* (persistent-PGD) ablations. This is what the repo implements today. -- **SPD** — Stochastic Parameter Decomposition — [`papers/Stochastic_Parameter_Decomposition/spd_paper.md`](papers/Stochastic_Parameter_Decomposition/spd_paper.md). Predecessor; introduced the causal-importance / stochastic-masking framing VPD builds on. Concepts still right, but VPD supersedes it. -- **APD** — Attribution-based Parameter Decomposition — [`papers/Attribution_based_Parameter_Decomposition/apd_paper.md`](papers/Attribution_based_Parameter_Decomposition/apd_paper.md). Original precursor; introduced linear parameter decomposition. - -## Package layout - -ONE generic library, `param_decomp/`. **The library is just a library — mostly pure -functions, mostly just logic**; nothing infra-ish (schedulers, submission, cluster -paths, code-shipping) lives in it. The library is the deliverable — everything in it is -written to be shippable: - -The distribution is `param-decomp`; the package is enumerated layers, each a subpackage, -importing only DOWNWARD (pinned by `param_decomp/core/tests/test_runtime_standalone.py` -— an allowlist; a new subpackage must be enumerated there deliberately): - -- `core/` — the generic JAX single-pool VPD trainer ENGINE (`run.py` = - `run_decomposition_training`, `model.py` = the `DecomposedModel` protocol, - `train.py`, `ci_fn.py`, …; ZERO concrete target code) plus the torch-free pydantic - config SCHEMA it reads directly (`base_config.py`, `schedule.py`, `configs.py` = - `PDConfig` / `Cadence` / loss + eval-metric configs) and the built-run bundle - (`built_run.py`). No `main()`, no YAML — takes built objects. -- `targets/` — every `DecomposedModel` implementation, one slice per architecture: - `glu_transformer.py` (+ `llama8b.py`/`qwen3_8b.py` family files), - `llama_simple_mlp.py`, `transformer_taps.py`, the toys `tms.py`/`resid_mlp.py`; - per-target parity/golden suites in `targets/tests/`. Imports core only. -- `vendored_jax/` — bit-parity JAX archs (leaf; excluded from typecheck). -- `pretrain/` — the in-house target-LM pretrainer (`python -m - param_decomp.pretrain.train`). -- The composition/consumer layers (the former lab, merged in): `experiments/` (the - per-domain composition roots + YAML authoring schemas — `python -m - param_decomp.experiments.lm.run ` is the LM in-job entry), - `harvest/`, `autointerp/`, `clustering/`, - `topology/`, `adapters/`, `migrations/`, `infra/`. Library-level tests in - `param_decomp/tests/`. - -**Datasets are named, never located.** `data.train` / `data.eval` carry -`{kind: name, name: }` and resolve under `/datasets//`. A dataset -dir is self-describing — `meta.json` (`infra.dataset_store.DatasetMeta`: seq_len + -tokenizer) rides with the shards, so the config carries only the identity. Names are -immutable versions: a changed dataset is a new name. A dataset is born by materializing -shards + meta, which `prestage_tokenized` writes together. - -`make install-dev` installs the library editably, with dev deps, into the one `.venv`. -The library ships no console scripts — every runnable surface is a module main. -Slow/plot eval is in-loop only: it has no entry point of its own. - -## The library rule - -`param_decomp` is JUST a library: logic and mostly-pure functions over explicit inputs. -It may do I/O that *is* the work — checkpoints, datasets, HF weights, wandb logging, -LLM calls — but it must not know *where it runs*: no scheduler (SLURM/sbatch), no -submission or code-shipping, no cluster paths, mounts, partitions, or team namespaces. -Deployment fit belongs to whatever launcher invokes the library. A launcher composes -library entrypoints and may import the library; the library may never import a launcher -(enforced fail-closed by `param_decomp/core/tests/test_runtime_standalone.py`). The -library reads NO ambient environment for paths: output roots are explicit, required -parameters threaded from entry points, so a launcher passes its own resolved root as an -argument. Credentials and third-party-tool conventions (`WANDB_*`, `*_API_KEY`, `HF_*`, -`CUDA_*`) may follow their ecosystem's own env contract, resolved at entry points. -Everything else takes typed values. A launcher is not privileged: if it needs -something the library doesn't publicly expose, that is a library bug — never a reason -for a private hook. A SLURM *mention* in library prose is legitimate only when it -documents a generic contract (e.g. SIGTERM→save semantics), never a dependency. - -**Configs are portable: names, never locations.** A config references the world only -through names — a dataset name, a run id, an HF hub id, a wandb ref — each with exactly -one resolver, rooted in a global registry (HF hub, W&B) or the explicit `data_root`. -Locations (absolute paths) are representable only inside tagged escape arms -(`data: {kind: dir, ...}`), so non-portability is always loud in the document; names -are immutable versions, so a pin means the same thing on every machine and every year. -CI-enforced for the seats (CONFIGS.md rule 5). Known tracked exception: -`resume_provenance.parent_run_dir` is an absolute path that should be a run id. - -## Training (JAX) - -**Training is JAX now.** The torch `Trainer` was retired from HEAD (the JAX single-pool -trainer is faster and is what we run; the torch trainer is preserved as the *semantic -oracle* at git tag `torch-oracle`). - -The trainer lives in `param_decomp/core/`. The semantics source of truth is its -`SPEC.md` (normative pseudocode + numbered invariants, grounded in the torch oracle — -JAX **conforms** to it). For the real entry points, read `param_decomp/core/CLAUDE.md` -and `param_decomp/core/SPEC.md`. In one breath: - -- **`DecomposedModel`** (`param_decomp/core/model.py`) — THE model interface: ordered `sites` + - pure `clean_forward` / `masked_forward` / `prepare_compute_weights` / `weight_deltas` - methods on an `eqx.Module` carrying frozen target weights as fields (trainable `vu` is an - explicit method arg). Core passes immutable capture-key frozensets into the forwards; the - target validates and canonicalizes them into its private slot layout when JAX first traces - the call. Every capture key names exactly one physical activation, and - `ForwardResult.captures` carries that one-to-one dictionary directly. Generic over LM and - toy targets. There is one recon semantics: - chunkwise masking through the full target-input forward, compared at the target output. -- **`run_decomposition_training(...)`** (`param_decomp/core/run.py`) — the generic ENGINE: the - one train loop every target runs through (init/restore/finetune/faith-warmup, the - recon-grid step factory, orbax checkpointing, schedules, metrics, in-loop slow eval, - SIGTERM-save). A pure library — no `main()`, reads no YAML; takes built objects. -- **`python -m param_decomp.experiments.lm.run `** - (`param_decomp/experiments/lm/run.py`) — the LM composition root + only I/O layer: - reads the canonical schema, builds the target / data loader / `ExperimentConfig`, - then calls the engine. Orbax sharded checkpoints; SIGTERM → save → SLURM requeue → resume. -- **Topology derives from config; submission is a verb.** `dp <= gpus_per_node` → one - process over exactly `dp` local devices (asserted at startup); `dp > gpus_per_node` → - one process per node via `jax.distributed`. - `python -m param_decomp.experiments.lm.run ` runs HERE, in the current - allocation. Submission is somebody else's verb: an external scheduler owns it and - invokes this module inside the allocation it created. - -## Public API (consumer substrate) - -Alongside the trainer, `param_decomp/` exposes a thin substrate the **consumers** -(harvest / autointerp / clustering / intruder) lean on. Import names from where they're -defined — no package-level re-exports; `__init__.py` files are bare except two -deliberate exceptions (`topology/__init__.py` re-exports `path_schema_for_model_type`; -`adapters/__init__.py` defines the adapter constructors): - -```python -from param_decomp.core.configs import Cadence, LossMetricConfig, PDConfig -from param_decomp.core.log import logger -from param_decomp.experiments.lm.load_run import open_jax_run, run_metadata -from param_decomp.experiments.lm.runtime import RuntimeConfig -``` - -- `PDConfig` — algorithm config: seed, CI fn, loss metrics, optimizers, decomposition - targets. The torch-free pydantic schema now lives in core - (`param_decomp.core.configs`, alongside `base_config` / `schedule`); the engine reads the - derived runtime `ExperimentConfig` (`param_decomp.core.built_run`). (The eval-metric *config* - classes likewise live in `param_decomp.core.configs`; only their torch `Metric` *impls* were - dropped.) -- `RuntimeConfig` — the LM run's compute substrate (`runtime:`): `dp`, - `remat_recon_forwards` / `remat_ci_fn`, and `launch_env` (the pre-process env each rank - runs with — single source of truth, so `config.yaml` captures the run's environment). - Perturbs numerics without changing the algorithm. Composition-side - (`param_decomp.experiments.lm.runtime`): core accepts it in no form, and the toys have no - substrate to author. -- `param_decomp.core.log` — the logger every consumer uses (folded into the core trainer - package). -- `param_decomp.experiments.lm.load_run.{open_jax_run, run_metadata}` — the JAX - consumer entry (composition-side, since it builds the LM target): a run opened for a forward pass - (`open_jax_run`, restores orbax) or just its target topology (`run_metadata`: - `n_blocks`/`vocab`/per-site `(name, C)` from config + cache, no restore). `JaxPDAdapter` - keys autointerp/clustering metadata off `run_metadata`. - -The torch run-loading surface (`ComponentModel`, the loss `Metric` impls, `RunSink`, -`RunBatch` / `ReconstructionLoss`, `component_model_io`, the vendored archs) was dropped -and returns JAX-native as the #10 torch->jax adapter. - -## Where things live - -- `param_decomp/core/` — the JAX trainer engine. The pydantic config SCHEMA (`base_config.py` = - `BaseConfig` / `Probability`; `schedule.py`; `configs.py` = routing + - the explicit (toy) site spec + loss + eval-metric configs + `PDConfig` - / `Cadence` / `WandbConfig` / `ResumeProvenance` + the wandb-shaping helpers; the - authored `decomposition.ci` configs, the tiled LM site specs AND the LM's `runtime:` - substrate live with their domain schemas, composition-side). The - built-run bundle the engine consumes (`built_run.py`: `BuiltRun` / - `DataConfig` / `EvalConfig` / … + the `TargetSites` protocol). The engine + numerics - (`run.py` = `run_decomposition_training`, `model.py` / `train.py` / `ci_fn.py` / - `family.py` / `adversary.py` / `recon.py` / `losses.py` / - `checkpoint.py` / `sharding.py` / `init_placed.py` / `recon_eval.py` / `slow_eval.py` + - `log.py`) plus `configs/` - (the self-contained run yamls) and `tests/`. The concrete targets live in the sibling - subpackage `param_decomp/targets/` (`glu_transformer.py` + - `{llama8b,qwen3_8b}.py` family files, `llama_simple_mlp.py`, the toys - `{tms,resid_mlp}.py`; its `tests/` holds the frozen torch↔JAX equivalence goldens and - the other parity suites). The torch oracle lives at git tag `torch-oracle`. -- `param_decomp/pretrain/` — the in-house target-LM pretrainer (`python -m - param_decomp.pretrain.train`): trainable equinox archs whose `state_dict()` keys the - decomposition loader reads. -- `param_decomp/vendored_jax/` — bit-parity JAX Llama / GPT-2 archs the trainer - decomposes. -- `param_decomp/adapters/` — `JaxPDAdapter`: torch-free autointerp/clustering metadata - for a JAX run, keyed off `experiments.lm.load_run.run_metadata` (config + cache, no - orbax restore). The torch `build_target` bridge was deleted with the rest of torch. -- `param_decomp/experiments/` — `config.py` (the shared `ExperimentConfig` YAML - schema base — each domain subclass binds concrete `target`/`decomposition`/`data` — - plus the shared YAML→`ExperimentConfig` conversion). `experiments/lm/`: `run.py` (pre-JAX environment bootstrap — - `python -m param_decomp.experiments.lm.run`), `training.py` (the LM composition root), `config.py` - (LM schema + LM build), `resolved.py` (resolved LM data/run types), `load_run.py` (open a finished - JAX run), `eval.py` / `attn_patterns_eval.py` / `arithmetic_eval.py` / `data.py` / - `hf_http.py`, `data.py` / `prestage_tokenized.py` (offline tokenize → parquet shards). - The TMS and ResidualMLP domains live under `experiments/{tms,resid_mlp}/` - (`run.py` + `config.py`; module mains), calling the core engine as a - library over the toy targets (`param_decomp/targets/{tms,resid_mlp}.py`). -- `param_decomp/{harvest,autointerp,clustering}/` - — post-pipeline stages, each with its own CLAUDE.md. -- `param_decomp/infra/` — settings, paths, wandb, sqlite, run_files, markdown, - tokenizer_display, pydantic helpers. - -## Module pointers - -| Module | CLAUDE.md | What it covers | -|---|---|---| -| `param_decomp/experiments/` | `param_decomp/experiments/CLAUDE.md` | LM `target.spec` schema, the offline prestage tool, JAX launch | -| `param_decomp/harvest/` | `param_decomp/harvest/CLAUDE.md` | Component-statistics collection pipeline | -| `param_decomp/autointerp/` | `param_decomp/autointerp/CLAUDE.md` | LLM-based component interpretation | -| `param_decomp/clustering/` | `param_decomp/clustering/CLAUDE.md` | Hierarchical clustering of components | - -> **The torch web-app (`param_decomp/app/`) was temporarily removed during the JAX -> migration** to shed torch surface for the JAX-primary merge. It is slated for re-add, -> likely as a JAX-native viewer. The reusable tokenizer-display helpers it once owned -> (`AppTokenizer`, `escape_for_display`, `delimit_tokens`) now live in -> `param_decomp/infra/tokenizer_display.py`. See the removal PR for the full re-add log. - -## Saved-run layout - -Every artifact for a decomposition lives under one dir per run: - -``` -/runs// - launch_config.yaml # the single self-contained run config (the trainer reads it; resume byte-compares). NOT config.yaml: that basename collides with wandb's reserved run-config file, which wandb.save would symlink onto and clobber - ckpts//{decomposition,training}/ # orbax sharded checkpoints (JAX trainer): the trained product vs the trainer-only tail (pre-split default/-item runs need an ad-hoc migration, no in-code compat) - metrics.jsonl # local logs - harvest/h-*/... # harvest output - autointerp/a-*/... # autointerp output -``` - -Both training output and the W&B download cache write here. Per-stage subdirs are -populated by their respective pipelines. - -`data_root` is the ONE root of the library's local world — runs (outputs), the dataset -store, the pretrain and compilation caches all hang under it. It is an explicit, -required parameter, never an env var and never defaulted: every entry edge (composition -roots, worker mains, consumer functions like `open_jax_run`) refuses to run without it, -so a deployment cannot silently write into a cwd-relative directory. A launcher passes -its resolved root explicitly — the `--data_root` / `--data-root` flag, or the -pretrainer's stamped `data_root`. - -## Development commands - -**Use `make test` for the default inner loop.** It uses testmon to rerun only tests affected -by the current changes and excludes `slow`; do not run a bare full-workspace `pytest` while -iterating. Use `make test-all` for exhaustive validation. - -| Command | Purpose | -|---|---| -| `make install-dev` | Library + dev deps + pre-commit, into the one `.venv` (see [Environment](#environment)) | -| `make install` | Library only, no dev deps | -| `make check` | basedpyright + ruff lint + format | -| `make type` | basedpyright over `param_decomp/` | -| `make format` | ruff lint + format | -| `make test` | Tests excluding slow | -| `make test-all` | All tests | - -Run a single test: `python -m pytest path/to/test_file.py::test_name`. - -## CLI entry points - -The library ships no console scripts: every runnable surface is a module main, run -inside whatever allocation your scheduler gave you. LM training is -`python -m param_decomp.experiments.lm.run` (JAX). Slow/plot eval is in-loop only (no -entry point). - -| Command | Entry point | Purpose | -|---|---|---| -| `python -m param_decomp.experiments.lm.run` | `param_decomp/experiments/lm/run.py` | The LM decomposition composition root (reads YAML, builds the target, calls the core engine) | -| `python -m param_decomp.pretrain.train` | `param_decomp/pretrain/train.py` | The core in-house target-LM pretrainer | -| `python -m param_decomp.experiments.lm.run_targeted` | `param_decomp/experiments/lm/run_targeted.py` | The TARGETED (tPD, SPEC §11) LM decomposition root — takes the targeted run shape (`prompts:` + `nontarget:`); refuses a plain config | -| `python -m param_decomp.experiments.{tms,resid_mlp}.run` | `experiments/{tms,resid_mlp}/run.py` | The CPU toy decomposition composition roots | -| `python -m param_decomp.harvest.scripts.{run_worker,run_merge,run_intruder}` | `harvest/scripts/` | Component-statistics harvest: per-rank worker, merge, intruder eval | -| `python -m param_decomp.autointerp.scripts.run_interpret` | `autointerp/scripts/` | LLM interpretation of harvested components | -| `python -m param_decomp.clustering.scripts.{run_worker,run_merge,calc_distances}` | `clustering/scripts/` | Clustering harvest / merge / consensus distances | +- [`README.md`](README.md) — installation, runnable entry points, datasets, packaging, and development commands. +- [`CONFIGS.md`](CONFIGS.md) — which configurations belong in the repository and how they stay portable. +- [`param_decomp/core/SPEC.md`](param_decomp/core/SPEC.md) — the trainer's normative numerical contract. +- The nearest module-level `CLAUDE.md` — local architecture and interfaces. These exist under `core`, `experiments`, `harvest`, `autointerp`, and `clustering`. -The toy run commands (`experiments.{tms,resid_mlp}.run`) accept `--group ` (wandb -group field, used for UI collapsing) and `--tags a,b,c`. Both no-op when `wandb:` is -omitted from the YAML. The LM and pretrain roots take their wandb group and tags from -the config's `wandb:` block instead. +## Repository-wide constraints -## Files to skip when searching +- `param_decomp/` is the public library. It must not know where it runs: no scheduler, submission, code-shipping, cluster path, mount, partition, or team namespace. Paths are explicit required inputs, and configs identify external resources by portable names. Deployment adapters may depend on the library; the library may never depend on them. +- Current training is JAX. The retired Torch implementation is only a semantic oracle at git tag `torch-oracle`; `nano_param_decomp/` is a standalone Torch reference and is not imported by either package. +- Keep the functional core pure and put I/O at entry points. Encode invariants in types when possible and assert the rest. Fail closed rather than adding fallbacks, compatibility shims, or degraded modes. +- Import public names from the modules that define them; package-level re-exports are exceptional. Update the nearest guide or specification when changing a documented structure or interface. -Use `param_decomp/` as the search root, not the repo root. +## Development -Always skip: `.venv/`, `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `node_modules/`, -`.git/`, `.data/`, `wandb/`, `notebooks/`. +`make install-dev` installs the library and development tools into one environment. Run commands with `uv run` or activate `.venv`. -Usually skip unless relevant: the `tests/` subtrees (`param_decomp/core/tests/`, -`param_decomp/targets/tests/`, `param_decomp/tests/`), `papers/`. +Use the narrowest useful check while iterating: ---- - -# Coding guidelines - -This is research code, not production. Prioritize simplicity and fail-fast over -defensive programming. - -## Fail fast - -- If you have an invariant in your head, **assert it**. Asserting isn't a sign you - distrust the code — it's the opposite. Codify the trust. -- Don't write `if everything_is_ok: continue_happy_path()`. Just `assert everything_is_ok`. -- Have a VERY good reason to handle an error gracefully. If the program isn't working as - it should, it shouldn't be running — fix it instead. -- Avoid `try/except` unless it's the right tool. Never use it for control flow. -- Write for the golden path. Don't pre-handle edge cases — raise instead, and handle - them when they actually bite. - -```python -# BAD -def get_config(path: str) -> dict | None: - try: - with open(path) as f: - return json.load(f) - except: - return None - -# GOOD -def get_config(path: Path) -> Config: - assert path.exists(), f"config not found: {path}" - with open(path) as f: - return Config(**json.load(f)) # pydantic validates +```bash +make test # testmon-selected tests, excluding slow +make check # ruff format/lint and basedpyright +make test-all # exhaustive suite ``` -## No legacy support - -- Don't add fallbacks for old formats or migration shims. Change it; migrate manually - if needed. -- Delete unused code. If an argument is always the same value, inline it. -- **"Unused" is judged against the right caller set.** The two rules above apply to - internal code, whose callers are enumerable in-repo. Config schema fields, CLI flags, - and other user-facing surface have users the tree deliberately does not contain: - uncommitted sweeps and stored runs' pinned `launch_config.yaml`s (see CONFIGS.md — the - repo's job is more than running committed configs). "No committed config sets it" is - not evidence for removal; before deleting external surface, check the canonical seats, - stored-run pins, and intent. The fix for an untested capability flag is a test, not - deletion. - -## Types & arguments - -- Encode invariants in types. If two fields jointly vary (both present or neither), - put them in an optional tuple — don't make them independently optional. -- Avoid `| None` unless null is semantically meaningful. Differentiate `None` from `[]` - when it matters. -- Don't use bare dicts for heterogeneous values. `{: }` good; `{"tokens": ..., - "loss": ...}` bad — use a dataclass. -- PEP 604 unions (`X | Y`, `X | None`) — not `Union[X, Y]` or `Optional[X]`. -- Lowercase generics (`list`, `dict`, `tuple`) — not `List`, `Dict`, `Tuple`. -- Type-checker: **basedpyright** (not mypy). -- Don't use `from __future__ import annotations`. Use quoted forward references when needed. -- Don't add redundant annotations (`x: int = 5` when `x = 5` infers fine). -- Default arguments are rarely a good idea. Have a very good reason — especially if the - caller also defaults to the same value. Keep defaults high in the call stack. -- Be explicit about naming, even if names end up long. If a name has to be long to be - honest about what the thing is, that's fine — if it feels silly, the abstraction is - probably wrong upstream. - -## Control flow - -- Keep I/O as high as possible. Make as many functions pure as possible. -- Prefer `match` over `if/elif/else` for dispatching on a tag or kind — more declarative. - -## Tensor operations - -- Prefer einops for clarity. -- Use jaxtyping for shape annotations (we don't runtime-check, but they document). -- Assert shapes liberally. - -## Comments - -Comments hide sloppy code. If you feel a comment coming on, consider: better names, -extract a function, extract a named local. - -Comments describe what the code is, not what changed about it. No narrativizing: - -- `# the function now uses y instead of x` — bad -- `# changed to be faster` — bad -- `# we now traverse in reverse` — bad - -**Comments point inwards, not outwards.** A comment carries a constraint, invariant, or -gotcha the code itself can't show. It must not narrate transient outward state: -campaign measurements tied to a particular config ("~5x at the production plan"), -strategy attributions ("per Oli: no TP"), PR war stories, current-canon claims. That -content lives in lore, the PR thread, or an in-repo design doc (which MAY carry -history) — with at most a short pointer from the code. SPEC invariant-ID citations -(`S14`, `D4`, …) are sanctioned and required as before. - -## Docstrings - -Docstrings carry information the signature doesn't. - -- Default to a single line — or none at all, even on public classes / configs / - functions, when name + type carry everything. `class DistributedState:` doesn't need - `"""Immutable snapshot of the distributed runtime state for this process."""`. -- Skip `Args:` / `Attributes:` entries that just paraphrase the name and type. -- Don't restate the function name in English. If the name needs translation, fix the name. -- Keep: non-obvious semantics, invariants, gotchas, shape constraints not in jaxtyping, - side effects, ordering requirements, cross-references. -- No Sphinx/RST markup. Single backticks, not double. -- No `Raises:` for `AssertionError` — asserts are programmer errors, not part of the - contract. -- Don't re-document a Protocol or abstract method in its impl unless there's - impl-specific behavior to note. -- Module docstrings: one orienting line. Anything longer belongs in CLAUDE.md. - -**Load-bearing public entrypoints in `param_decomp/` are an exception** — there, a full -Google-style `Args:` block is worth the bookkeeping, because IDE hover surfaces it and -the callers are external. Concretely: `run_decomposition_training`, the -`DecomposedModel` protocol methods, `open_jax_run` / `run_metadata`. For everything else, -*including internal helpers in `param_decomp/`*, prefer better parameter names and -clearer parameterisation over docstrings — name parameters by their role inside the -function, not just their type. - -## Tests - -Tests catch obvious bugs; they're not insurance against production outages — there's -no production. Skip heavy end-to-end tests when they require lots of overhead. The -codebase is run interactively constantly, so the user catches issues cheaply. - -## Other - -- **Update CLAUDE.md files** when changing code structure, adding/removing files, or - modifying key interfaces. Update the CLAUDE.md in the same directory (or nearest - parent) as the changed files. - -## GitHub - -- Use `gh` for issues and PRs (`gh issue view 28`, `gh pr view 30`). -- PR template: `.github/pull_request_template.md`. -- Before committing: verify you're on the right branch. Don't `git add .` — add - specific files. -- Branch names: `refactor/X`, `feature/Y`, `fix/Z`. -- **Never** `--no-verify`. Pre-commit hooks exist for a reason. If they fail, fix the - underlying issue. +Never bypass pre-commit hooks. Add files explicitly rather than with `git add .`. diff --git a/README.md b/README.md index ae34d6845..bc8b955dc 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,13 @@ Training tools for parameter decomposition on neural networks. For a compact implementation of the core method, see [`nano_param_decomp/`](nano_param_decomp/). +## Research guidance + +Read the [parameter-decomposition handbook](docs/handbook.md) for the +science, evidence standards, and failure modes. The +[parameter-decomposition skill](docs/skill.md) is the experiment-driving +guide for target implementation, sweep design, convergence, selection, and analysis. + ## References - **VPD paper (April 2026):** https://www.goodfire.ai/research/interpreting-lm-parameters. [VPD Code Release](https://github.com/goodfire-ai/param-decomp/releases/tag/vpd-paper) diff --git a/docs/handbook.md b/docs/handbook.md new file mode 100644 index 000000000..57def0978 --- /dev/null +++ b/docs/handbook.md @@ -0,0 +1,173 @@ +# Parameter Decomposition — Handbook + +The single source of knowledge on parameter decomposition — interpretability in parameter space: why mechanisms are sought in the weights rather than the activations, what a parameter decomposition is and the properties that make one trustworthy, the evidence standards and failure modes, and what a finished decomposition licenses downstream (subcomponent interpretation, attention analysis, attribution graphs, clustering, model editing). The [parameter-decomposition skill](skill.md) carries the executable recipe; this handbook carries the science. Parameter decomposition is causal ablation carried out in *parameter* space. + +## Summary + +Parameter decomposition splits a neural network's weights into parameter components — vectors in parameter space — such that each component implements a small piece of the network's learned algorithm, only a few components are needed on any given input, and the unneeded components can be ablated, in any combination, without changing the output. It lets us say *"these are the parts of the weights that this behavior causally depends on"*. + +It differs from activation-space interpretability: instead of using featurizers first to look for the representations (variables) on which computations might be done, parameter decomposition identifies the objects doing the computations first, and then asks what representations they use. It uses a learned *causal importance function* to estimate the causal importance of each parameter component on a given input. The causal importance is the degree to which a parameter component *cannot* be ablated without affecting the output (1 = not ablatable at all; 0 = fully ablatable). + +## Why decompose parameters + +**Architectural units are not mechanisms.** Neurons, attention heads, and layers do not reliably map to individual, interpretable computations: representations span neurons, spread across heads, and stretch over layers. A neuron-by-neuron account of a network is perfectly accurate and useless — unnecessarily long, phrased in polysemantic parts, carving the network nowhere near its joints. + +**Activation-based decompositions train replacement models.** Sparse dictionary methods (SAEs, transcoders, cross-layer transcoders) fit a *different* function — wider, differently non-linear — to the transitions between activations. This has produced real insight into intermediate representations, but the account it gives is hard to relate to the objects doing the computing: the network's parameters and nonlinearities. The mismatch is practical, not just aesthetic: a replacement model with more representational capacity than the original can learn representations that the original could not computationally distinguish (feature splitting is one symptom), and it gives no direct handle for making precise, predictable *edits* to the model's algorithm. + +**Parameter space is mechanism space.** During learning, gradient descent iteratively etches a neural network’s mechanisms into its parameter vector, which makes it natural to look for mechanisms in parameter space. Parameter space satisfies several necessary properties that 'mechanism space' must have: it spans the functional range from "does everything the network does" (the full parameter vector) to "does nothing" (the zero vector); it accommodates mechanisms that are not aligned with neurons, heads, or layers; it accommodates computation in superposition (more mechanisms than neurons); and it accommodates multidimensional mechanisms (mechanisms that operate on multidimensional representations, such as multidimensional manifolds). + +**What the stance buys.** It strives to identify mechanisms, i.e. *steps in the network's algorithm*. A non-circular footing for "features": features are *properties of the input that activate particular mechanisms* — a definition that does not depend on human interpretability or choice of featurizer. Structural immunity to feature splitting: subcomponents marked causally unimportant must be ablatable *in any combination*, so the decomposition cannot invent ever-finer sparsely-activating parts the way a dictionary can — a split part's siblings would be jointly ablatable only when none of them is real (and this is verified empirically: added capacity goes unused rather than splitting). Architecture-agnosticism: attention layers decompose by the same procedure as MLPs, and the resulting parts routinely span multiple attention heads — distributed attention computations become analyzable instead of invisible. And a direct substrate for editing: the parts are weights, and weights are the network, which is what we wanted to understand, rather than the dataset on which it operates. + +## What a parameter decomposition is + +### The objects + +Each weight matrix \(W^l\) is decomposed into a sum of **rank-one subcomponents** \(\vec{U}^l_c (\vec{V}^l_c)^\top\) — each a "read" direction \(\vec{V}\) paired with a "write" direction \(\vec{U}\). The number of subcomponents per matrix may exceed the matrix's rank; that headroom is exactly what lets the decomposition capture mechanisms in superposition. **Components** are clusters of subcomponents that tend to be causally important together; a component may span several matrices and layers, and is the object that deserves the name "mechanism". Subcomponents are not components — but individual subcomponents are often interpretable on their own, and much analysis proceeds at the subcomponent level. **Δ-components** parametrize the residual between the summed subcomponents and each target (original) matrix; they are defined to be causally unimportant everywhere and tend to be small. + +Bias parameters in the target model are currently left undecomposed. Their causal importance is fixed at 1 on every input. + +A **causal importance function** — itself a trained neural network — maps the target model's hidden activations to a **causal importance value** \(g^l_c \in [0,1]\) for every subcomponent at every sequence position. Causal importance is defined by *ablatability*: \(g = 0\) means the subcomponent can be fully or partially ablated on this input without changing the model's output; \(g = 1\) means it cannot be ablated at all. Ablations are implemented with masks \(m = g + (1-g)r\) with \(r \in [0,1]\), so an important subcomponent's mask is pinned to 1 while an unimportant one may be scaled anywhere down to 0. + +### The four properties + +A decomposition is trained toward four properties. If it exhibits all four, its components are strong candidates for the network's mechanisms. + +- **Parameter faithfulness** — the components sum to the target network's parameter vector. A *static* property of the decomposition, checked by direct comparison (and by the unmasked model matching the target). This is stricter than behavioral equivalence: different parameters can produce the same behavior, but only the actual parameters are the actual mechanisms. +- **Minimality** — as few subcomponents as possible are causally important on any given input. This is what makes the decomposition a *simplification*: each datapoint's computation is described by a small subset of components. +- **Mechanistic faithfulness** — every subset of components that includes the causally important ones computes the network's output: the causally *un*important components are ablatable **in any combination**, partially or fully, *including combinations chosen adversarially to break the output*. A *behavioral* property, checked by intervention. Keep it distinct from parameter faithfulness — one says the components add up to the weights, the other says the importance labels survive being acted on. +- **Simplicity** — each component contains as little computational machinery as possible. The rank-one constraint carries most of this, plus a slightly superlinear penalty on how **frequently** a subcomponent is important — without it, unrelated mechanisms used on disjoint data can hide inside a single rank-one subcomponent (their sum can itself be rank one). In the current JAX objective this frequency pressure has its own coefficient and reference-token count; it is not a `beta` nested inside the importance penalty. Description length of the *parameters* used per datapoint is the operative measure, and it is just a proxy for what we ultimately want — to minimize the description length of the *computation*. + +**Why "ablatable in any combination" is the defining requirement.** Two failure cases show why weaker criteria don't suffice. + +- *Joint ablation only.* Suppose unimportant components only had to be ablatable *all together*. Then a pair of components whose contributions cancel could both be labeled unimportant — ablating both together changes nothing — even though each is individually load-bearing: ablate either one alone and the output changes. The labels are wrong, and anything downstream that trusts them (an edit that removes one "unimportant" component, a circuit account that drops it) breaks the model. Demanding output invariance along *every* partial-ablation path catches the pair and correctly forces both labels to "important". +- *No ablation-combination requirement at all.* Drop the requirement and a spurious decomposition scores perfectly on every other property: invent one low-rank component per datapoint, tuned to reproduce that datapoint's output, plus one residual component to restore parameter faithfulness. This giant lookup table of the training set is perfectly parameter-faithful, *maximally* minimal (exactly one component important per input — minimality actively rewards it), and even survives the joint-ablation check, since each datapoint's component reproduces the output on its own. Only any-combination ablatability kills it: a permitted combination that leaves other datapoints' shards partially unablated sums to an arbitrary parameter vector and wrecks the output. Components must not interfere with the computation on data they are not important for — so general machinery cannot be split into memorized shards. + +The same property is what allows explanations to **aggregate**: if two inputs are each explained by their own subset of components, the union of the subsets still (approximately) computes both — so local explanations of single behaviors can compose into global accounts of the model. + +**Why adversarial checking is part of the definition.** All possible mask combinations cannot be enumerated, so the property is checked by sampling. Stochastic (uniform) sampling bounds the *average* case; the property is about *every* case, and decompositions trained only against stochastic masks reliably harbor mask settings — findable by a gradient-based adversary — that destroy the output while touching only "unimportant" components. Adversarially-chosen ablations are therefore part of what mechanistic faithfulness *means* operationally, not merely an optional hardening. + +### Two senses of "active" + +Keep two notions apart when reading any analysis. **Causal importance** (\(g\)) says the subcomponent is *needed* — but it is not a local measure; a subcomponent can interact strongly with the activations and have its effect suppressed downstream. **Subcomponent activation** (\(a^l_c = \lVert\vec{U}^l_c\rVert (\vec{V}^l_c)^\top \vec{\varphi}^l\)) measures the local interaction between the input activations and the subcomponent's read direction, whether or not it ends up mattering. Superposition guarantees more interactions than important interactions, so high activation with zero importance is common and meaningful (interference), and interpretation work should lead with causal importance. + +*Terminology note:* earlier papers in this line use "attribution" for a gradient-based estimate of what is now measured directly as causal importance, and use "parameter component" for a full-parameter-vector object rather than today's cluster-of-subcomponents. This handbook and the skill use the current terms throughout. + +## The parameter-decomposition pipeline + +**Input.** A target model; the set of weight matrices to decompose; the data distribution the decomposition should hold over (usually the model's training distribution — the mechanisms found are relative to it); and the claim or downstream use the decomposition serves. + +**Pipeline.** + +1. **Scope the claim and calibrate the instrument.** What behavior or model is being decomposed, and what will the decomposition be used for — a mechanism inventory, a circuit question, an edit? The downstream use fixes the data distribution (an external dataset for LMs; a synthetic generator for toys) and the matrices worth decomposing. In a new domain, you should first decompose a target whose mechanisms are already known and verify that the method recovers them. This anchor is mandatory: under-training and an ill-matched reconstruction objective can both produce clean-looking nulls, so an unanchored target cannot distinguish between 'real absence of structure' and 'badly configured method'. +2. **Decompose, to convergence.** Train the subcomponents and causal importance function, sweeping the sparsity pressure (importance-minimality coefficient) — the right value is not knowable a priori. Runs must reach convergence; the sparsity penalty's schedule (Smooth-L0 `gamma`, or `pnorm` for the Lp variant) means minimality arrives late, and unconverged decompositions are not comparable to each other or to anything else. +3. **Validate against the evidence standards** (next section). A decomposition that fails them is not a weaker result to be reported with caveats; it is not yet a decomposition. +4. **Cluster subcomponents into components** where the analysis needs mechanism-level objects; skip when subcomponent-level analysis suffices (it often does). +5. **Analyze** (see *Working with a decomposition*): interpret subcomponents, trace circuits with attribution graphs, analyze attention behaviors, edit. +6. **Report** the tradeoff surface and the checks, not one flattering checkpoint. + +This repository carries the executable workflow for steps 2–3 and the later-stage tools. The [parameter-decomposition skill](skill.md) carries sweep design, smoke criteria, convergence checks, and result selection. + +## Evidence standards + +A good decomposition shows *worst-case* reconstruction under the strongest evaluation the domain implements **and** genuine minimality — the number of causally important subcomponents per datapoint (\(L_0\)) is small relative to a domain-appropriate baseline. Matrix rank is a useful scale for some LM sites, not a universal threshold: for a toy with known mechanisms, compare against the ground-truth number used by an input (for TMS 5→2, typically about one active feature), not against rank 2. Both must hold: low reconstruction error with needlessly high \(L_0\) is faithful but no simplification; low \(L_0\) with high reconstruction error is sparse but unfaithful. Verify parameter faithfulness separately: the *unmasked* model (all masks 1, Δ-components excluded) must match the target — if it doesn't, the components don't even sum to the model being explained. + +**The evaluation adversary is deliberately shaped.** Fresh adversarial masks at evaluation are stricter than the persistent adversary used in training, and they are *shared across the batch* on purpose: a fully per-datapoint adversary can exploit uncorrelated superposition-interference noise, so sharing forces it to find *systematic* defects in the decomposition rather than noise-fit single points. + +**Monitor, never optimize.** Reconstruction under causal-importance-values-as-masks, and under rounded (binarized) importances, indicate whether the components labeled important suffice on their own. They are informative *only because nothing optimizes them*: both are trivially driven to perfection if included in training, without the decomposition capturing anything. The adversarial loss (and, less so, the stochastic loss) is the term that resists this cheating. + +**How much adversarial robustness to demand is open.** Complete robustness is provably too strict: an unconstrained adversary can co-ordinate the interference noise of genuinely-inactive superposed circuits (ablate all negative-noise contributors, keep all positive ones) and change the output of a decomposition we should accept. The practical standard: the decomposition should be robust to the kinds of ablations you will actually perform — the component maskings used in analysis and editing, over the data you care about — rather than to arbitrarily strong per-datapoint attacks. Robustness to a modest adversarial budget, degrading gracefully as the budget grows, is the expected signature of an acceptable decomposition; report the budget alongside the number. + +**Convergence and metric discipline.** The minimality proxy sharpens over training (`gamma` decreases for Smooth-L0; `p` decreases for the Lp variant), so \(L_0\) falls steadily late into the run and the adversary takes many steps to bite — most of a decomposition's apparent quality is unreadable before convergence. End-of-run metric values are noisy point estimates; compare runs on windows of settled values, never single points, and treat the adversarial metric as the noisiest of all (read its plateau, not its last value). + +**Reconstruction is scored in the target's own output metric** — KL per position for a language model, MSE for TMS or ResidMLP, whatever a new domain's output space calls for. Report which metric a reconstruction number is in; values are not comparable across metrics, and a new domain earns its recon metric before it earns a Pareto front. + +**Minimality needs an anchor.** Use the strongest baseline the domain permits: + +| Domain | Minimality anchor | +| --- | --- | +| Closed or exhaustively verifiable target | Exact task accuracy under masking over the full input space, compared with chance; report the smallest sufficient set only among masks that preserve the target's exact accuracy. | +| TMS or another target with known mechanisms | Ground-truth number and identity of mechanisms used by each input. | +| Language model without mechanism ground truth | The reconstruction/minimality Pareto front, with matrix rank and the dense all-subcomponents count as scales rather than universal thresholds. | +| Classifier without mechanism ground truth | Architectural units (neurons, channels, or heads) under matched causal masking. Also target model- and chance performance. | + +A fair comparison with neurons or heads holds the target, data, mask family, reconstruction metric, and adversarial budget fixed; it compares active-unit count at matched reconstruction (or reconstruction at matched count), reports each method's unit granularity, and includes the dense and chance endpoints. Merely beating the architectural-unit count is not evidence of useful minimality: even an untrained hundred-step smoke can often clear a threshold that weak. If a bad or untrained baseline passes the stated bar, strengthen the bar before interpreting the decomposition. + +**Comparing decompositions and methods.** Compare on the tradeoff between sparsity and (eval) adversarial reconstruction — Pareto fronts across the sweep — and be explicit about the sparsity notion, since "one active unit" means different things across methods (a per-matrix subcomponent, a per-layer latent, a cross-layer latent). Interpretability comparisons use intruder detection on causal importances (thresholding tiny importances (e.g. 0.1) is legitimate — they carry almost no reconstruction). Feature-splitting tests: grow capacity and watch whether the number of alive subcomponents grows with it (splitting) or stays flat (headroom unused — the healthy signature). + +Seed-consistency (mean max cosine similarity across decomposition seeds) is evidence but not the goal: networks are highly degenerate, and there may be a *space* of mechanistically faithful decompositions rather than one ground truth — faithfulness, not uniqueness, is the property to insist on. Measure this first across decomposition seeds of the **same frozen target**. Before comparing decompositions of independently trained targets, characterize the target-training variance itself (task metrics, learned function, and transition timing where applicable); otherwise target non-reproducibility is indistinguishable from decomposition instability. + +**Quantify and report.** Cite every number to the run and artifact that produced it; report the sweep's tradeoff curve, the convergence evidence, the adversarial budget, and the monitor-only metrics — not a single selected checkpoint. Plot their curves over training — don't only report point estimates at the end. + +## Failure modes and false conclusions + +Diagnose these before interpreting anything; several masquerade as findings about the model. + +- **Causal-importance collapse.** Sparsity pressure too high: importance values sink below 1 everywhere, reconstruction blows up. Observable keys: `CIHistograms` has no mass near 1, `CIMeanPerComponent` has no alive shoulder, and eval `PGDReconLoss` rises. No subcomponent sitting at \(g \approx 1\) for most of its firing inputs is a tell. +- **Too-dense decomposition.** Sparsity pressure too low: `CI_L0` remains near the dense baseline at settled eval `PGDReconLoss`, with no useful simplification on the sweep's reconstruction/minimality Pareto front. +- **Polysemantic subcomponents.** Insufficient frequency pressure lets unrelated mechanisms share one rank-one subcomponent (often visible in per-subcomponent exemplars as two unrelated jobs keyed to the sign of its activation, while `ComponentActivationDensity` shows the component alive across both input classes). Raise the separate frequency-minimality coefficient to split them; it trades off against the importance pressure. Do not emulate this with the removed Torch-era `beta`. +- **Under-training read as "no structure".** An unconverged decomposition looks like a null result — `CI_L0` or eval `PGDReconLoss` are still falling, and the scheduled minimality shape parameter (`gamma` or `pnorm`) has not spent a settled window at its final value. Most apparent parameter-decomposition nulls are under-training; confirm these curves plateau before drawing any conclusions. +- **Privileged input basis mistaken for learned structure.** If the input representation is sparse in some basis, every readout looks structured in that basis; the test is per-unit selectivity against a random-direction control — a shuffled null does not catch it. +- **Dead subcomponents mistaken for a mechanism count.** The subcomponent budget \(C\) is deliberately over-provisioned; `CIMeanPerComponent` should show the alive/dead cutoff used for the estimate. The raw budget, `ComponentActivationDensity`'s count of units that ever fire, and a single thresholded checkpoint all mislead. + +If the sweep fails to identify a good decomposition, find better hyperparameters that work. They almost certainly exist. + +## Working with a decomposition + +What analysis a validated decomposition permits. This repository documents the runnable tooling; the doctrine is here. + +**Interpreting subcomponents.** Subcomponents activate for coherent categories of input, and are labeled the way features are — exemplars, automated labeling, intruder tests — but with causal importance in place of activation magnitude, and low-importance firings treated as background (they are mostly interference). Read both senses of "active" side by side: high activation with low importance is itself informative (the model *touches* the subcomponent but suppresses its effect). + +**Attention analysis.** Attention parameters decompose like everything else, and the resulting subcomponents routinely span multiple heads — making computations distributed across heads analyzable. The QK circuit factors into *pairs* of query- and key-subcomponents: a static, data-independent interaction strength (how strongly a pair contributes to attention scores, as a function of position offset) surfaces behaviors like previous-token and syntax-boundary attention; a data-dependent interaction strength decomposes any actual attention pattern into per-pair contributions that can be included, excluded, and ablated one at a time. OV circuits are compared across heads by the overlap of the subspaces they read from and write to, weighted by where the data actually varies. + +**Attribution graphs.** Circuits are traced by attributing each subcomponent's activation to upstream subcomponents — gradient × source activation × source importance, with gradients *stopped* through every non-source subcomponent so edges measure direct effects only. Two disciplines: (1) pruning a graph to a specific behavior must itself use adversarial sampling — graphs pruned with importances-as-masks alone are much smaller, reconstruct the behavior well, and are mechanistically unfaithful (adversarial masking of their discarded remainder destroys the prediction); (2) an attribution graph is *not* a computational graph — it records how strongly information flowed, not the function computed, and the nonlinear interactions between subcomponents at neurons remain the open frontier between current practice and full reverse engineering. + +**Clustering subcomponents into components.** Where mechanism-level objects are needed (and they so far have only rarely been needed), cluster subcomponents by co-importance: binarize causal importances, treat a group's importance as the OR of its members', and minimize a description-length cost that trades the index cost of a larger dictionary against the rank cost of fatter components, with a resolution knob (α) setting where that trade sits. Merging proceeds hierarchically and stochastically to escape greedy local minima. Clustering is a separate, potentially substantial compute cost at large subcomponent budgets; budget it independently from decomposition training and record the sampling/restart budget. It is post-hoc and its resolution is a choice — do not report a component count as a fact about the model without reporting the knob. + +**Model editing.** Each subcomponent's rank-one structure gives one read direction and one write direction, and either can be surgically replaced — e.g. pointing a write vector at a chosen unembedding direction rewrites what the mechanism *does* when it fires. Validate edits like interventions: measure the target behavior change *and* off-target divergence from the unedited model both near the edit's firing sites and globally. Hand edits currently trade off against trained baselines (a well-fed LoRA can win on off-target damage); the edit's value is interpretability and label-free precision, not dominance — and hybrid schemes are unexplored. + +**Training diffs.** Subcomponents are directions in parameter space, so any gradient update or finetuning diff can be projected onto the decomposition's basis — expressing what training did as upweighting, modifying, or creating mechanisms. Doctrine-only for now: no shipping recipe. + +## Limits of interpretation + +Allowed: + +- "These subcomponents are causally important for this behavior on this distribution, under maskings up to the stated adversarial budget." +- "This subcomponent is causally important on inputs of type X and ablatable elsewhere." +- "The causally important set is minimal and sufficient in the tested combinations; the unmasked decomposition reproduces the target model." +- "This edit changed the target behavior with off-target divergence of Y (surrounding) and Z (global)." +- "This attention behavior is implemented by these subcomponent pairs, distributed across these heads." + +Avoid: + +- "This component *is* the mechanism for X" from a decomposition alone — component identity depends on the clustering resolution, and semantic labels are hypotheses until tested like any feature label. +- "The model has N mechanisms" — dead-subcomponent counts depend on the budget, component counts on the clustering knob, and degeneracy may permit many valid decompositions. +- "The model has no parameter-space structure here" from an unconverged run or a single sweep point. +- Reading an attribution graph as the algorithm — flow strength is not functional form. +- Treating an importances-as-masks subgraph, here or in any masking-based method, as a faithful circuit without adversarial validation. +- "The decomposition is the unique ground truth" from seed consistency — faithfulness is the standard; uniqueness is not established. + +## Scope and maturity + +VPD's tuning maturity and validated results currently extend through 67M transformer language models, plus TMS and ResidMLP toys. Past that scale, do not summarize failure as a single size ceiling: say whether the observed blocker is **optimization** (no converged reconstruction/minimality Pareto point), **memory or runtime** (the intended run cannot complete), or **transfer** (settings from a smaller target converge but no longer yield a useful decomposition). + +The library's architecture coverage is broader than that evidence base: it ships runnable Llama- and Qwen-family 8B target implementations and decomposition recipes. Those 8B seats show that the architecture and execution path exist; they do not establish tuned, trustworthy 8B decompositions. Other architectures and datasets may require significant implementation and tuning work. But using parameter decomposition at scale is an open research frontier. + +## Background + +- *(Key paper) Interpreting Language Model Parameters* (Bushnaq et al., 2026) — the current method (VPD) and the downstream analyses summarized here: [https://static.goodfire.ai/vpd-blog-post/post.md](https://static.goodfire.ai/vpd-blog-post/post.md) + +Cite it as: + +```bibtex +@misc{bushnaq2026interpreting, + title={Interpreting Language Model Parameters}, + author={Bushnaq, Lucius and Braun, Dan and Clive-Griffin, Oliver and Bussmann, Bart and Hu, Nathan and Ivanitskiy, Michael and Linsefors, Linda and Sharkey, Lee}, + journal={Technical Report}, + institution={Goodfire and MATS}, + month={April}, + year={2026}, +} +``` + +- *Stochastic Parameter Decomposition* (Bushnaq, Braun & Sharkey, 2025) — rank-one subcomponents and the causal importance function. arXiv:2506.20790 +- *Interpretability in Parameter Space: Minimizing Mechanistic Description Length with Attribution-based Parameter Decomposition* (Braun et al., 2025) — the minimum-description-length framing and the faithfulness/minimality/simplicity criteria. arXiv:2501.14926 diff --git a/docs/skill.md b/docs/skill.md new file mode 100644 index 000000000..7e00526c6 --- /dev/null +++ b/docs/skill.md @@ -0,0 +1,155 @@ +# Parameter Decomposition + +This document is a practical guide to implementing, training, and evaluating a parameter decomposition with this repository. The science lives in the [parameter-decomposition handbook](handbook.md) — why mechanisms are sought in the weights rather than the activations, the four properties a trustworthy decomposition must exhibit (parameter faithfulness, minimality, mechanistic faithfulness, simplicity), the evidence standards and failure modes, and what a finished decomposition licenses downstream. + +## Implementing a target + +The core trainer is agnostic to target architecture: it drives anything satisfying the `DecomposedModel` protocol (`param_decomp/core/model.py`), including the target-owned reconstruction metric `recon_loss_fn`. **Expect to implement your own target, and often your own composition root.** The targets that ship with the library (TMS and ResidMLP toys, a 4-layer Llama-style LM, GLU-transformer targets loading Llama-3.1-8B / Qwen3-8B-Base HF weights) are working examples from our own research. Read the one nearest your shape before writing yours, and fit the library to your problem rather than your problem to these examples. The reconstruction comparison rides on the target, not on config: `recon_loss_fn` is a static method on your `DecomposedModel`, and every recon term — the training losses and the fresh-PGD eval probe alike — scores through it. The LM targets return `kl_per_position`; TMS and ResidMLP return MSE. Use what your output space calls for, and implement it if nothing shipped matches your shape. + +This is a research repo. When the library is awkward or gets in your way, patch your checkout directly and note the diff + +In some cases, you may be able to use the included implementations of target models and composition roots. The runnable roots are [`param_decomp/experiments/lm/training.py`](../param_decomp/experiments/lm/training.py) for LMs, [`param_decomp/experiments/tms/run.py`](../param_decomp/experiments/tms/run.py) for TMS, and [`param_decomp/experiments/resid_mlp/run.py`](../param_decomp/experiments/resid_mlp/run.py) for ResidMLP. They are thin wrappers around the core trainer that load the config, target, and data. [`param_decomp/experiments/toy_eval.py`](../param_decomp/experiments/toy_eval.py) only binds authored toy evaluation operations; it is not a runnable composition root. In general, treat the included implementations as references, and use the universal library entrypoint `param_decomp/core/run.py` when writing your own root. + +To implement a target model, + +- Check for an existing JAX implementation to start from — many language models have JAX implementations on HuggingFace or elsewhere. +- `core/model.py` is the contract. Read it in full, docstrings included, before writing a line — it carries the waist geometry, the mask semantics, and the per-method requirements. +- For an LM-shaped target, start from `param_decomp/targets/llama_simple_mlp.py` and copy its structure; read `SyntheticDecomposedModel` in `param_decomp/core/tests/test_generic_model_io.py` (~120 lines, driven through the real train step) when you want the protocol with nothing else attached. Every shipped `DecomposedModel` lives in `param_decomp/targets/` — when you reuse a module from one, read it first; each bakes in its own family's choices (attention flavor, positional encoding, norm placement). +- Verify the port against an independent reference forward — a torch implementation when one exists, a float64 NumPy forward you write from the architecture spec otherwise; the value of the oracle is its independence from your JAX code. The repo's parity-golden machinery is the shape to copy: frozen goldens under `param_decomp/targets/tests/`, with `qwen3_hf_parity/gen_hf_fixtures.py` as a turnkey generator (tiny-random and `--real` modes, its docstring carries the torch-venv recipe). +- **On GPU, set `jax_default_matmul_precision = "highest"` for parity checks**: fp32 matmuls default to TF32 on Ampere+, and a correct port will fail every gate with depth-growing deviation that looks exactly like a wrong block. Check parity on the real target as well as any tiny fixture — the TF32 effect grows with depth, and a 3-layer fixture can read as rounding noise. +- Before allocating any GPU: parse your config through the experiment schema and run the placement assertions (`assert_placement_claims`) on CPU. Schema, loss-builder, and placement failures are all free to find statically, and their assertion messages are the documentation. + +For agents: If you cannot establish an equivalent `DecomposedModel` implementation of the target model, do not continue, and explain to the user. + +## Recipe + +Mapping from our conceptual-level losses (from the handbook) to their (sometimes multiple) instantiations. + +- **Parameter faithfulness:** `FaithfulnessLoss`. The squared elementwise error between the component sum and the target weights, averaged over the total decomposed parameter count. Equivalently, the (normalized) sum of squared values in the ∆-component. +- **Minimality:** `ImportanceMinimalityLoss` (Lp), or the newer `SmoothL0ImportanceMinimalityLoss`. Also measured using L0 as a non-differentiable eval. +- **Simplicity** — implemented as the nested `frequency:` block on the two importance-minimality losses above. +- **Mechanistic faithfulness:** Reconstruction Loss, of which there are many different variations. Loss configs take the rough form `*Recon*Loss`, with the wildcards expanding to variations. Fundamentally a reconstruction loss asks "how well does the decomposition approximate the target model's behaviour" but this leaves unbound various details. There are numerous schemes for masking causally unimportant subcomponents (stochastic masking, adversarial masking, raw CI-value masking), and many other tweaks which improve training dynamics, for example only using the decomposition parameters for a subset of the model, as in our `*ReconSubsetLoss`es or `*ReconLayerwiseLoss`es. In *Interpreting Language Model Parameters*, VPD uses separate stochastic and adversarially masked reconstruction passes, but this is just one potential combination of many valid configurations. + +A good default which we have recently settled on: + +- `FaithfulnessLoss` +- `SmoothL0ImportanceMinimalityLoss` + `frequency` term +- `MergedStochasticSubsetPPGDReconLoss` — a compound loss combining adversarial (PPGD) and stochastic (StochasticSubset) reconstruction into one pass. + +The 4L-Pile reference config (`param_decomp/experiments/lm/configs/pile_llama_simple_mlp-4L.yaml`) carries this recipe with tuned coefficients; the toy reference configs carry the same shape at their own coefficients. In general you should start with a reference config nearest your target. + +The most important hyperparameters are not knowable a priori, so **the default arc is to sweep the importance-minimality coefficient** (`SmoothL0ImportanceMinimalityLoss.coeff`). Depending on the pathologies this surfaces, sweep `frequency.coeff` or the subcomponent budget `C` separately. Runs must go to convergence — analyzing or comparing unconverged decompositions is almost always worthless. + +### 0. Background + +Fresh LM decompositions are usually compute-heavy and often need several sweep rounds. + +#### Setting hyperparameters for sweeps + +| Hyperparameter | Reference value | When to change | +| :---- | :---- | :---- | +| **Importance-minimality coeff** — `pd.loss_metrics[SmoothL0ImportanceMinimalityLoss].coeff` | `8e-4` (TMS 5→2); `6e-5` (TMS 40→10); `2e-4` (4L-Pile flagship) | **Most sensitive — sweep this first.** Too high → CI collapses below 1 and recon blows up; too low → too many subcomponents fire per input. | +| **Component / CI learning rate** — `pd.components_optimizer.lr_schedule.start_val` and `pd.ci_fn_optimizer.lr_schedule.start_val` | `1e-3` both (TMS); `5e-5` both (4L-Pile flagship; cosine →10%) | Standard LR tuning. The flagship keeps the two equal; we vaguely think components at ~3× the CI-fn LR is a good starting point in LMs — unswept, a hunch rather than a tuned fact. | +| **Frequency-minimality coeff** — `...[SmoothL0ImportanceMinimalityLoss].frequency.coeff` | `4e-4` (TMS 5→2); `3e-5` (TMS 40→10); `1e-4` (4L flagship) | Keep near half the importance-minimality coeff initially. Lower → fewer, more polysemantic subcomponents. **This is an independent loss coefficient; there is no frequency `beta` like in the paper.** | +| **Smooth-L0 width schedule** — `...[SmoothL0ImportanceMinimalityLoss].gamma` | linear `1.0 → 0.01` | Annealing sharpens the smooth active-count proxy over training. Copy the whole schedule from the flagship config unless intentionally studying it. | +| **Subcomponents `C`** — toy `decomposition.sites.sites[*].C`; LM `decomposition.sites.cs.` | TMS 5→2: `20` per site; TMS 40→10: `100`; LM: see the C table below | Start from the matching shipped config. For LMs, calibrate down from a converged `CIMeanPerComponent` spectrum; usually keep C at or above the matrix rank — below rank, exact faithfulness is structurally impossible. | +| **Δ-L2 parameter-faithfulness coeff** — `pd.loss_metrics[FaithfulnessLoss].coeff` | `1` (TMS); `1e7` (4L flagship) | Insensitive; raise 10× until `kl_unmasked` is negligible. Overshooting is safe within reason, but an excessively large value can still impair optimization — stop raising once `kl_unmasked` is flat. | + +Each decomposed matrix gets a subcomponent budget at `decomposition.sites.cs.`. The matrix names are the site vocabulary of `decomposition.sites.kind`. The shipped 4-layer simple-MLP reference (`d_resid = 768`; scale with width) uses: + +| Module | `C` per layer | +| --- | ---: | +| `c_fc` (MLP up, 768×3072) | 3072 | +| `down_proj` (MLP down, 3072×768) | 3584 | +| `q_proj`, `k_proj` (768×768) | 768 | +| `v_proj` (768×768) | 1024 | +| `o_proj` (768×768) | 1024 | + +The shipped 32-layer GLU-transformer reference (`d_model = 4096`) uses `q: 2048`, `k: 2048`, `v: 4096`, `o: 4096`, `gate: 8192`, `up: 8192`, and `down: 10240` per layer; see [`llama8b_full32L_HSDP_b64_dp64.yaml`](../param_decomp/experiments/lm/configs/llama8b_full32L_HSDP_b64_dp64.yaml). These are reference budgets, not universal defaults: scale them for the target width and architecture, and start from the matching shipped config when one exists. + +In general, we think a safe approach early in tuning is to make C slightly larger than the maximum dimension of a given matrix. It certainly should be larger, usually, than the rank of the matrix, otherwise faithfulness becomes structurally impossible. + +So, for an LM with no close reference, over-provision and do a converged run, then read the `CIMeanPerComponent` spectrum: there's usually a sharp alive/dead cutoff after training, where a long tail of subcomponents have mean ci below ≈1e-6 or 1e-7. We take this to reveal a rough estimate of the count of the "alive" subcomponents. Aim within ~2× of it. + +For toy models, do not use this LM heuristic. E.g. for TMS we use `20` per site for 5→2 and `100` for 40→10, which deliberately exceeds the known feature count. + +### 1. Define the experimental plan + +Fix the following decisions before launching an experiment: + +- **Domain and runtime** — identify the target model. Confirm that the public JAX package can be installed in the execution environment. TMS and ResidMLP run on CPU and need no GPU; any non-toy experiments will normally need GPU compute. +- **LM target** (`target`) — `weights_dtype` (required, no default) plus a `spec`. Use `bfloat16` unless you have a reason not to: `float32` works, but it drops off cuDNN flash attention, so an 8B target materialises the `[B, H, T, T]` scores and will likely OOM rather than error. +- **Data distribution** +- **Base config** — the reference config plus the values for hyperparameters that matter +- **Sweep grid (optional)** — the axes and their values (see step 2). +- **Selection rule** — Choose it by domain. For an LM without ground truth, use the converged reconstruction/minimality Pareto front; a reasonable default is the lowest importance coefficient whose adversarial recon stays below a stated threshold while `CI_L0` is materially simpler than the relevant dense baseline. For TMS, use the ground-truth target-CI metric and expected feature pattern below — the toys do emit a fresh-PGD recon scalar on their own MSE metric, but ground truth outranks it whenever it exists. +- **Compute plan** — first decide whether GPUs are needed at all: TMS and ResidMLP use CPU; LM sweeps usually use GPUs. Record grid size × steps × devices; later rounds may be needed. + +For agents: Get explicit approval from your operator on these points before going ahead with costly experiments. + +### 2. Define the grid — 1D over the coefficient + +Sweep the importance-minimality coeff first. Too low gives many active subcomponents; too high collapses CI and breaks reconstruction. For LMs, the useful region has low `CI_L0` and low adversarial recon loss; for toys, use the runner's ground-truth metric and reconstruction training loss. Use about five log-spaced points centered on the relevant reference and bracket roughly an order of magnitude either side. The grid must be wide enough to expose both pathologies; add points if the Pareto front is too coarse. **With VPD it is better to take longer than to trust a faulty decomposition.** + +Keep the first sweep one-dimensional. Hold `frequency.coeff`, `gamma`, and the domain's `C` fields fixed. If a later frequency sweep is needed, sweep its coefficient directly — there is no `beta` — while holding the importance coefficient fixed. Over-provision `C` on a first run, and reduce it only after a converged run shows a stable alive/dead cutoff. + +### 3. Happy-path test one point, then launch the full sweep + +A useful initial test must do more than set `steps: 50`. Schedules use normalized progress, so truncating 400k steps to 1k fully anneals them on a compressed schedule rather than reproducing the first 1/400th of the reference run. The test must pass faithfulness warmup, perform a PD or adversarial update, fit in memory under the intended CPU/GPU topology, and run an evaluation pass. For LMs, include the slow evaluation pass. For toy models, include the configured evaluation and the runner's ground-truth metric. Launch the complete sweep after one configuration passes these checks. + +Run sweep configurations to convergence. Compare hyperparameters only after the relevant metrics plateau, even when that happens before the full step count. Stop a clearly dominated configuration early when doing so frees substantial compute. + +Confirm convergence before interpreting anything. **For LMs:** eval `PGDReconLoss` plateaued, `CI_L0` settled at a meaningful simplification relative to the relevant dense baseline, and `kl_unmasked ≈ 0`. **For toys:** training losses and the in-loop ground-truth metric settled; do not wait for LM eval metrics the runner does not compute. + +- *PGD-recon is not plateauing or L0 is still falling:* the run needs more steps. If stochastic reconstruction and average PPGD training loss look good but adversarial PGD reconstruction is poor during evaluation, strengthen the persistent-PGD training loss (`PersistentPGDReconLoss`, or the merged loss's adversarial term). Increase `n_warmup_steps` for more inner Adam ascents per training step; total ascents are `n_warmup_steps + 1`. `optimizer.lr_schedule` controls the ascent learning rate. Lower the learning rate proportionally when increasing the ascent count. The training loss has no `n_steps` or `step_size`; those settings belong to the evaluation probe. +- *Importance-Minimality collapsed, recon blew up* → importance minimality coeff too high. +- *L0 remains high relative to the domain's expected active-mechanism count or sweep Pareto front* → Importance-Minimality coeff too low. +- *kl_unmasked not ≈ 0* → the unmasked subcomponent sum isn't reproducing the target → check parameter faithfulness (`FaithfulnessLoss`). At sufficiently good faithfulness loss kl_unmasked should be ≈0 by construction. Remember this will be impossible if C < rank in your target parameters. + +## What a good result looks like, and how to check it + +- **Good result:** (This is key info) + - Adversarial **PGD-recon** (`PGDReconLoss`; freshly initialized masks, ~20 PGD steps) has *plateaued* low — mechanistically faithful in the worst case, not just on average — **and** **L0 per datapoint** (`CI_L0`) has settled `≪` matrix rank, so it is an actual simplification. Both must hold. VPD trains against a persistent PGD adversary that warm-starts its attack across steps; run quality is judged on the separate stricter eval probe: the `PGDReconLoss` entry in `eval.metrics` with `init: random` and `source_shape: c`, reinitialized fresh at each eval. Why the eval adversary is fresh and shared across the batch, and how much adversarial robustness to demand, are covered in the [handbook's evidence standards](handbook.md#evidence-standards). +- **Verify:** the unmasked model matches the target — `kl_unmasked ≈ 0` (the output KL of the all-components-on model vs the target, logged by `CEandKLLosses`) — this is the **parameter-faithfulness** check; if it fails, raise the Δ-L2 coefficient (`FaithfulnessLoss`) and inspect the Δ component. The `CIMeanPerComponent` spectrum shows a sharp alive/dead cutoff and at least some CI values sit ~1 for most inputs (if none do, the importance minimality coefficient is too high); a known mechanism, if you have one, comes back as expected (an inserted identity matrix → one high-rank component). +- **Metric noise should be accounted for:** The end-of-training value of training/eval metrics is just a point estimate of a noisy quantity. Plot the metric curves over training and compare runs on windows of settled values — don't compare single end-of-run point estimates; you risk just comparing noise. +- **Monitor but do not optimize CI-masked and rounded-CI-masked reconstruction.** These metrics test whether the causally important set is sufficient. Keep them out of the training loss because optimization can trivially drive them near zero; see the [handbook](handbook.md#evidence-standards). Stochastic reconstruction is a training term. Use its evaluation counterpart, `kl_stoch_masked`, as the average-case result while noting that it is optimized. Adversarial PGD reconstruction is the stronger check against this failure. +- **Failure mode that superficially looks informative (but is not):** + - *Under-training read as "no structure."* Minimality arrives late while the Smooth-L0 `gamma` schedule sharpens (the reference anneals `1.0 → 0.01`), and the adversary takes many steps to bite. If using `ImportanceMinimalityLoss` instead, its `pnorm` schedule plays the analogous role (canonical `2.0 → 0.4`). For LMs, confirm PGD-recon and L0 have settled; for toys, confirm the training losses and target-CI metric have settled. Most apparent VPD nulls are under-training. + +If no runs in the sweep look good, reason through how to modify the hyperparameters in order to fix the observed pathologies, and run a new sweep. Do not proceed to downstream analysis until you've got hyperparameters that you're confident are good. + +For agents: If the new sweep materially changes or expands the approved compute plan, get explicit approval from your operator before launching it. + +### Eval metrics: the canonical block + +The eval pass is **authored-only**: exactly the metrics listed in `eval.metrics` run, and nothing silently re-adds one you drop. LM runs should keep the flagship's full **metric list**; the block's sizing knobs are yours — `eval.batch_size` is a **global** batch (scale it to your allocation, like the training batch). Four gates the schema enforces: each metric's logged identity must be unique — its `name` if it has one, otherwise its `type`, so a second `PGDReconLoss` probe at different `n_steps` is fine provided you `name` it — eval entries must not set a `coeff` (training-only), `CI_L0` requires `groups` (write `groups: null` for none), and the cadences must nest — `eval.every` a multiple of `cadence.train_log_every`, and `eval.slow_every` a multiple of `eval.every`. + +| Metric | What it logs | How to read it | +| :---- | :---- | :---- | +| `CEandKLLosses` | Output-level faithfulness battery under `eval/ce_kl/`: `kl_` for all six variants — `unmasked`, `ci_masked`, `rounded_masked` (CI binarised at the required `rounding_threshold`), `stoch_masked`, `random_masked`, `zero_masked` — plus `ce_difference_` for the same set *minus* `zero_masked`, so six `kl_` keys and five `ce_difference_` keys. LM-only: these keys read next-token CE and KL over a categorical output distribution. The toy binding refuses the metric outright, but the LM binding's only construction-time guard is `has_position_axis` — a positioned non-categorical target clears it and logs meaningless numbers, so omit this metric unless your target emits logits. | The workhorse. `kl_unmasked ≈ 0` = parameter faithfulness holds. `kl_stoch_masked` = the headline average-case recon number for comparing runs. `kl_rounded_masked` low = the binarised causally-important set alone suffices. For cross-model comparison, normalize the `kl_` numbers against the `kl_zero_masked` ceiling yourself (there is no `ce_difference_zero_masked` to normalize against). | +| `PGDReconLoss` (`init: random`, `n_steps: 20`, `step_size: 0.1`, `source_shape: c`) | Fresh 20-step adversarial attack at eval, with one source shared across batch and positions. `step_size` is required, and only `init: random` with `source_shape: c` executes — anything else asserts at construction. An optional `name` sets the logged key (the flagship logs `eval/loss/PGDReconLoss_20step`). Copy the whole entry from the flagship. | The strict quality bar (see "What a good result looks like"). By far the *noisiest* metric — read the plateau/trend, never a single point. The 20-step budget is pragmatism, not principle: the working assumption is that robustness to 20 steps is enough, and at large scale the attack is still climbing well past 20 steps — treat absolute levels with suspicion. | +| `CI_L0` (per-layer `groups` + `total`) | Mean active CI values per position | Compare runs on the **Pareto plot of L0 versus reconstruction KL**. Runs on the same tight Pareto front represent similar-quality hyperparameter tradeoffs. | +| `CIMeanPerComponent` | Sorted mean-CI-per-component spectrum (linear + log) | Sharp alive/dead cutoff ≈ true component count → calibrates `C` (see the C table above). No values near 1 → imp-min coeff too high. | +| `ComponentActivationDensity` | Per-layer histogram of each component's firing density | Alive-vs-dead split; a smear with no bimodality = components aren't specializing. | +| `CIHistograms` | Per-layer histograms of CI values (lower-leaky + pre-sigmoid) | Want mass piled at 0 and near 1; everything pinned strictly below 1 = CI collapse (coeff too high). | +| `StochasticHiddenActsReconLoss` / `CIHiddenActsReconLoss` | Per-module hidden-activation MSE under stochastic / CI masks | Localizers: when output KL is bad, these tell you *which module's* reconstruction is failing. Monitor-only. | + +Check every metric above and record the anomalies you find. If one shows the run is broken, launch another sweep that tests a fix rather than stopping at the breakage alone. + +## Analysis of a decomposition + +For agents: Depending on what the user wants, you might at this point choose to perform different analyses. + +For agents: Show the key metrics and their plots to the user, and discuss why they indicate that the decomposition is acceptable or not. It will usually be a presentation of acceptability, because if you didn't find a good decomposition on one sweep, you should typically continue with more sweeps in order to find hyperparameters that work. + +Assuming your decomposition looks good according to the various metrics, the next step is typically the 'visualization' of the parameter subcomponents. This involves highlighting 'activating dataset examples', where activating here means both 'the subcomponent is causally important on these dataset examples' and 'the subcomponent has a subcomponent activation above a threshold'. You should typically visualize both of these as separate options. For causal importances, the subcomponent should be considered active if it has a causal importance above 0.0, whereas for the subcomponent activation, the threshold is set heuristically (e.g. anything with magnitude larger than 0.5 standard deviations (±) of the subcomponent activation for that subcomponent counts as 'active'). + +Another standard analysis is the visualization of the QK circuit. Details of this analysis can be found in the VPD paper. In particular, you should display plots of 'Standardized Static Interaction Strength' for pairs of subcomponents (where you should display each head separately as well as one aggregate measure of SSIS), and dynamic interaction strength, where you should display the contributions of various pairs of subcomponents to the attention scores of each head. You should show this by displaying the attention scores and attention patterns of each head as heatmaps, which vary according to the datapoint you display. Visualization should let users explore a number of different input datapoints, which should result in a number of different heatmap arrays. Further descriptions can be found in the VPD paper. + +Another standard analysis you should consider performing is running inference on the model with and without particular interpreted subcomponents, and observing the change in behavior. Users often use VPD in order to be able to interpret the effects of weight changes in their model, and this analysis is a first step in that direction. + +## Background / citations + +The [parameter-decomposition handbook](handbook.md) carries the science and cites the literature — the method implemented here is VPD, from *Interpreting Language Model Parameters* (Bushnaq et al. 2026: [https://static.goodfire.ai/vpd-blog-post/post.md](https://static.goodfire.ai/vpd-blog-post/post.md)). + +**From subcomponents to components.** A run produces rank-1 *subcomponents*. The *components* (the learned "mechanisms" this skill keeps referring to) come from clustering co-activating subcomponents — a separate step via the clustering pipeline (MDL clustering + stochastic hierarchical merging; you pick the merge threshold α), needed when the analysis wants mechanism-level objects. "Components" are groups of subcomponents that tend to be 'used' together by the network. But subcomponents are often useful objects for interpretability by themselves.