chanind commited on
Commit
d957f7f
·
verified ·
1 Parent(s): cb06631

Upload folder using huggingface_hub

Browse files
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/DECISIONS.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tree SAE (Gemma-2-2b, 32k) — interpretation & deviation ledger
2
+
3
+ Module: `benchmark/methods/train/tree_sae.py`. Paper: Cao et al., arXiv:2605.07922
4
+ (v2). Starting point: Kirill's synthetic-scale clean-room port
5
+ (`synth_sae_bench_baseline/experiments/synthetic/synthsaebench/tree_sae/`, ledger
6
+ `PAPER_DERIVED_DECISIONS.md`, cited below as "ledger #N"). Markers: **PE** paper-exact,
7
+ **PI** paper-inferred, **CR** clean-room choice, **KIRILL** = unchanged from his ledger,
8
+ **CHANGED** = differs from his implementation.
9
+
10
+ ## Architecture / forward pass
11
+ - One shared encoder/decoder + one bias; features partitioned layer-major into 4 privilege
12
+ layers (§4 "Tree Structure"; ledger #1). **PE / KIRILL**
13
+ - Widths `[2048, 4096, 12288, 14336]` = paper's `[1536:3072:9216:10752]` (App. C) = exact
14
+ 1:2:6:7 ratio scaled to 32768 (the twin's width). **PE ratio / PI scale**
15
+ - Per-layer TopK `[105, 21, 13, 11]` (sum 150 = twin k): paper's 4-layer L0=80 row
16
+ `[56, 11, 7, 6]` (Table 1) × 150/80 = `[105, 20.6, 13.1, 11.3]`, rounded. The paper's own
17
+ rule (round the per-prefix L0 of a matched Matryoshka) was not run. **PI**
18
+ - **TopK before gate** (Eq. 6: `f*` "is subsequently utilized as the final activation"); the
19
+ realized L0 can fall below 150 (ledger #4). **PI / KIRILL**. Override `gate_before_topk:
20
+ true` runs the per-layer TopK on gate-allowed candidates instead (realized L0 == k when
21
+ enough allowed features are positive). Evidence for that reading: Table 1 lists the Tree
22
+ SAE per-layer L0s as exact integers, and the 4M-token smoke run under the default reading
23
+ had layers 2-3 almost silent (L0 0.012 / 0.001 of 13 / 11) because children of randomly
24
+ assigned sparse parents rarely survive the gate. Not "clearly" stated, so the default is
25
+ unchanged. **OPEN**
26
+ - Recursive gate `f*_i = f_i · 1[f*_parent > 0]`, root-attached features ungated (Eq. 6);
27
+ layers gated in ascending order so the recursion is exact. **PE / KIRILL**
28
+ - Bias added exactly once per cumulative reconstruction `xhat_{<=l} = b + Σ_{t<=l} xhat_t`
29
+ (ledger #6). **PI / KIRILL**
30
+ - Reconstruction loss `Σ_l ||xhat_{<=l} − x||²`, batch mean (Eq. 7; ledger #7). **PE / KIRILL**
31
+
32
+ ## Auxiliary loss
33
+ - Per-layer TopK-style aux loss (Eq. 8), aux-k 256 (App. C). **PE**
34
+ - `α_1..4 = 1/128` — the paper's stated Gemma-2-2b setting (App. C: "setting auxiliary
35
+ coefficient as α_{1,2,3,4} = 1/128 ... can be beneficial on ... Gemma-2-2b"). Kirill used the
36
+ GPT-2 recipe `[1/32, 0, 0, 0]`. **PE (Gemma) / CHANGED**
37
+ - Aux features = top-256 DEAD features of the layer by **ungated** ReLU pre-activation
38
+ (ledger #9). **CR / KIRILL**
39
+ - Aux target is the **detached** residual `(x − xhat_{<=l}).detach()`: the paper says it uses
40
+ "the auxiliary loss proposed by Gao et al. (2024)", whose reference implementations (and
41
+ SAELens/Matryoshka) reconstruct a detached residual so the aux term does not push the
42
+ primary weights. Kirill did not detach. **PI / CHANGED**
43
+ - Nothing is dead before 10M tokens have been seen (ledger #16), so the aux loss is inactive
44
+ for the first ~2441 steps of a 4096-token-batch run. **PI / KIRILL**
45
+
46
+ ## Dynamic allocation
47
+ - Capacity `C_p` += per-example primary cumulative loss for every example on which `p` fires
48
+ (final gated act > 0); aux excluded; running sum from the start, never reset (ledger #10,
49
+ #11). **PI / KIRILL**
50
+ - Accumulator dtype: batch increment `loss @ fires` in fp32 on GPU, added into a **float64**
51
+ accumulator. The task spec said fp32; a 500M-token fp32 running sum of O(1e5) per-token
52
+ losses would exceed fp32's 24-bit mantissa and silently drop increments. **CR / CHANGED
53
+ (Kirill: fp64 on CPU)**
54
+ - Firing statistics (`fire_count`, batch-granularity `last_fire` token stamps) are int64 on
55
+ GPU; all per-step bookkeeping is vectorised (`fires.sum(0)`, one mat-vec, one `where`).
56
+ - Parent eligibility: firing rate ≥ 1 per 50,000 tokens, running rate from the start of
57
+ training (App. G; ledger #12). **PE rule / PI window**
58
+ - Dead = no positive final activation in the most recent 10M tokens (App. G; ledger #16).
59
+ **PE**
60
+ - Greedy Algorithm 1 (heap, max-min payoff), tie-break smaller feature id (ledger #14).
61
+ Candidate parents for layer l = ALL features of earlier layers (`m_l`). **PE / CR tie**
62
+ - Only DEAD children are reassigned; live edges never touched; first-fit in ascending parent
63
+ id into eligible parents whose LIVE child count is below `k*`; unplaceable dead children
64
+ keep their parent (App. G "first fit", "less than the optimal number of non-dead child
65
+ features"; ledger #15). Implemented as a vectorised `repeat_interleave` slot list — same
66
+ result as Kirill's pointer loop. **PE / KIRILL**
67
+ - **Root child quota (Gemma option, App. G)**: "Optionally, we can enforce a prerequisited
68
+ number of child features for the root node at l=0 ... helps reducing number of dead
69
+ features in Gemma-2-2b". The paper gives no value. Implementation: at every reallocation
70
+ event, layer l reserves `q_l = floor(root_child_quota_frac · s_l)` ROOT slots (default
71
+ 1/16 → 256/768/896); the greedy distributes the remaining `s_l − q_l` among eligible
72
+ learned parents; ROOT deficit slots (`q_l − live root-attached children`) are filled
73
+ FIRST by dead children, then learned parents. Not applied at initialisation. `0` restores
74
+ Kirill's no-quota behaviour (ledger #13). **CR value / CHANGED (Kirill: none)**
75
+ - Reallocation schedule: first event after 3000 steps, interval ×2 after each event, capped
76
+ at 10,000 (App. C "increase the interval by two"; ledger #17) → events at steps 3000, 9000,
77
+ 19000, 29000, … (13 events in 122,070 steps). The schedule state (`realloc_interval`,
78
+ `next_realloc_step`) is checkpointed. **PI / KIRILL**
79
+ - Dead-to-root event once the 1-based step count reaches `0.5 · total_steps` (step 61,035;
80
+ App. C "at half of the training"; ledger #18). **PI**
81
+ - Per-step order: optimizer update → statistics update → reallocation (if due) →
82
+ dead-to-root (if due), as in Kirill's loop.
83
+ - Initial allocation: every non-first-layer feature gets a uniformly random parent among all
84
+ earlier-layer features (dedicated CPU `torch.Generator`, seed `cfg.seed`); no eligibility
85
+ filter at init; first layer → ROOT (ledger #19). **PI / KIRILL**
86
+
87
+ ## Optimisation / numerics
88
+ - Adam, lr 1e-4, betas (0.9, 0.999), eps 1e-8, constant LR, no warmup/decay/clipping
89
+ (App. C; ledger #22). **PE lr / CR defaults**
90
+ - Decoder rows unit-norm: per-row tangent-space gradient projection before the update,
91
+ renormalisation after; the whole-model gradient is NOT normalised (App. C "normalise the
92
+ gradient as well as the decoder vector"; ledger #20). **PI / KIRILL**
93
+ - Init: kaiming-uniform decoder rows normalised to unit norm, encoder tied (`W_dec.T`),
94
+ zero bias (ledger #21). **CR / KIRILL**
95
+ - Batch 4096 tokens and 500M tokens are fixed by the driver (twin recipe); the paper used
96
+ batch 5120. **CR (driver)**
97
+ - Forward/backward under `torch.autocast("cuda", bfloat16)`, fp32 master weights and Adam
98
+ state; losses computed in fp32; per-layer TopK selection runs on bf16 pre-activations.
99
+ Kirill trained in fp32. Exported-model `encode` runs in fp32 without autocast. **CR / CHANGED**
100
+
101
+ ## Metrics, export, hierarchy
102
+ - `step` returns: `loss`, `recon_loss` (Eq. 7), `aux_loss`, `mse` (per-element MSE of the final
103
+ cumulative reconstruction), `l0` (mean gated-active features per token, all layers),
104
+ `l0_layer{0..3}`, `n_dead`/`frac_dead` (dead mask at the start of the step),
105
+ `n_root_attached` (non-first-layer features whose parent is ROOT), `n_realloc_events`,
106
+ `dead_to_root_done`.
107
+ - Export: `weights.safetensors` (`W_enc` (d_in, n), `W_dec` (n, d_in) unit rows, `b`),
108
+ `allocation.json` (parent per feature, ROOT = −1; layer per feature; dead mask),
109
+ `config.json` (config, step, tokens, event log). Flattened latent index = feature index.
110
+ - `ExportedTreeSAE.encode(x)` = final gated activations of raw residuals;
111
+ `native_ancestors()` = `{child: {parent}}` from the final allocation, root-attached
112
+ features contribute no edge, no graded score (ledger #25); `latent_level()` = privilege
113
+ layer. **PE**
114
+ - Checkpoint (`state_dict`): weights, Adam state, allocation vector, capacities, fire counts,
115
+ last-fire stamps, tokens seen, schedule state, dead-to-root flag, event log, generator
116
+ state, step → exact resume (test `test_checkpoint_roundtrip_reproduces_next_step`).
117
+
118
+ ## Open uncertainties (author questions in Kirill's `AUTHOR_QUESTIONS.md` still apply)
119
+ - Root quota value and fill order (CR here); TopK-before-gate; capacity semantics/reset;
120
+ aux residual detach; whether "increase the interval by two" is ×2; Adam schedule.
121
+
122
+ ## Gemma 500M run: gate BEFORE TopK (decided 2026-09-14)
123
+
124
+ The 500M-token run uses `gate_before_topk: true`. Evidence: the paper's
125
+ Table 1 reports Tree SAE per-layer L0s as exact integers equal to the
126
+ configured per-layer K ([21, 5, 4, 2], [26, 6], ...), which is only possible
127
+ if the recursive gate is applied first and TopK then selects K survivors per
128
+ layer; with TopK first the realised L0 is below K and non-integer (our
129
+ smoke run: [105, 2.3, 2.7, 2.2] vs [105, 21, 13, 11] with gate-first).
130
+ Kirill's frozen synthetic reading (TopK first) is kept available via the
131
+ override for comparison.
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # tree_sae_32k_k5_seed0
2
+
3
+ Architecture `tree_sae` trained on google/gemma-2-2b layer 12 (`model.layers.12`, resid_post) with the twin-SAE recipe: 499,998,720 tokens of chanind/pile-uncopyrighted-gemma-1024-abbrv-2B, batch 4096 tokens, context 1024.
4
+
5
+ Load with `model.py::load_exported(export_dir)` from this folder (see `interface.py`); `encode(x)` takes raw residual activations and returns the flattened latents; `native_ancestors()` gives the architecture's own parent claims. Interpretation decisions vs the paper are in `DECISIONS.md`; `config.json`/`log.jsonl` are the training config and metrics.
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "arch": "tree_sae",
3
+ "run_name": "tree_sae_32k_k5_seed0",
4
+ "n_tokens": 500000000,
5
+ "batch_tokens": 4096,
6
+ "total_steps": 122070,
7
+ "overrides": {
8
+ "gate_before_topk": true,
9
+ "layer_ks": [
10
+ 2,
11
+ 1,
12
+ 1,
13
+ 1
14
+ ]
15
+ },
16
+ "seed": 0,
17
+ "init_seed": 0,
18
+ "group": [
19
+ "hsae_32k_k5_seed0",
20
+ "tree_sae_32k_k5_seed0",
21
+ "hsae_forest_32k_k5_seed0"
22
+ ],
23
+ "trainer_config": {
24
+ "d_in": 2304,
25
+ "layer_widths": [
26
+ 2048,
27
+ 4096,
28
+ 12288,
29
+ 14336
30
+ ],
31
+ "layer_ks": [
32
+ 2,
33
+ 1,
34
+ 1,
35
+ 1
36
+ ],
37
+ "aux_k": 256,
38
+ "aux_alphas": [
39
+ 0.0078125,
40
+ 0.0078125,
41
+ 0.0078125,
42
+ 0.0078125
43
+ ],
44
+ "root_child_quota_frac": 0.0625,
45
+ "lr": 0.0001,
46
+ "adam_betas": [
47
+ 0.9,
48
+ 0.999
49
+ ],
50
+ "adam_eps": 1e-08,
51
+ "dead_token_window": 10000000,
52
+ "parent_eligibility_rate": 2e-05,
53
+ "realloc_first_interval": 3000,
54
+ "realloc_growth": 2,
55
+ "realloc_cap": 10000,
56
+ "dead_to_root_frac": 0.5,
57
+ "seed": 0,
58
+ "autocast_bf16": true,
59
+ "gate_before_topk": true,
60
+ "n_latents": 32768,
61
+ "layer_starts": [
62
+ 0,
63
+ 2048,
64
+ 6144,
65
+ 18432
66
+ ]
67
+ }
68
+ }
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/export/allocation.json ADDED
The diff for this file is too large to render. See raw diff
 
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/export/config.json ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "arch": "tree_sae",
3
+ "config": {
4
+ "d_in": 2304,
5
+ "layer_widths": [
6
+ 2048,
7
+ 4096,
8
+ 12288,
9
+ 14336
10
+ ],
11
+ "layer_ks": [
12
+ 2,
13
+ 1,
14
+ 1,
15
+ 1
16
+ ],
17
+ "aux_k": 256,
18
+ "aux_alphas": [
19
+ 0.0078125,
20
+ 0.0078125,
21
+ 0.0078125,
22
+ 0.0078125
23
+ ],
24
+ "root_child_quota_frac": 0.0625,
25
+ "lr": 0.0001,
26
+ "adam_betas": [
27
+ 0.9,
28
+ 0.999
29
+ ],
30
+ "adam_eps": 1e-08,
31
+ "dead_token_window": 10000000,
32
+ "parent_eligibility_rate": 2e-05,
33
+ "realloc_first_interval": 3000,
34
+ "realloc_growth": 2,
35
+ "realloc_cap": 10000,
36
+ "dead_to_root_frac": 0.5,
37
+ "seed": 0,
38
+ "autocast_bf16": true,
39
+ "gate_before_topk": true
40
+ },
41
+ "n_latents": 32768,
42
+ "layer_starts": [
43
+ 0,
44
+ 2048,
45
+ 6144,
46
+ 18432
47
+ ],
48
+ "step": 122070,
49
+ "tokens_seen": 499998720,
50
+ "n_dead": 2226,
51
+ "n_root_attached": 10671,
52
+ "events": [
53
+ {
54
+ "kind": "realloc",
55
+ "step": 3000,
56
+ "tokens_seen": 12288000,
57
+ "layers": [
58
+ {
59
+ "layer": 1,
60
+ "n_dead": 3584,
61
+ "n_moved": 3584,
62
+ "n_eligible_parents": 467,
63
+ "k_star_sum": 3840,
64
+ "root_quota": 256,
65
+ "n_to_root": 256
66
+ },
67
+ {
68
+ "layer": 2,
69
+ "n_dead": 11010,
70
+ "n_moved": 11010,
71
+ "n_eligible_parents": 987,
72
+ "k_star_sum": 11520,
73
+ "root_quota": 768,
74
+ "n_to_root": 768
75
+ },
76
+ {
77
+ "layer": 3,
78
+ "n_dead": 13015,
79
+ "n_moved": 13015,
80
+ "n_eligible_parents": 2006,
81
+ "k_star_sum": 13440,
82
+ "root_quota": 896,
83
+ "n_to_root": 896
84
+ }
85
+ ]
86
+ },
87
+ {
88
+ "kind": "realloc",
89
+ "step": 9000,
90
+ "tokens_seen": 36864000,
91
+ "layers": [
92
+ {
93
+ "layer": 1,
94
+ "n_dead": 1579,
95
+ "n_moved": 1579,
96
+ "n_eligible_parents": 467,
97
+ "k_star_sum": 3840,
98
+ "root_quota": 256,
99
+ "n_to_root": 1
100
+ },
101
+ {
102
+ "layer": 2,
103
+ "n_dead": 9682,
104
+ "n_moved": 9682,
105
+ "n_eligible_parents": 1780,
106
+ "k_star_sum": 11520,
107
+ "root_quota": 768,
108
+ "n_to_root": 240
109
+ },
110
+ {
111
+ "layer": 3,
112
+ "n_dead": 11879,
113
+ "n_moved": 11879,
114
+ "n_eligible_parents": 3691,
115
+ "k_star_sum": 13440,
116
+ "root_quota": 896,
117
+ "n_to_root": 189
118
+ }
119
+ ]
120
+ },
121
+ {
122
+ "kind": "realloc",
123
+ "step": 19000,
124
+ "tokens_seen": 77824000,
125
+ "layers": [
126
+ {
127
+ "layer": 1,
128
+ "n_dead": 35,
129
+ "n_moved": 35,
130
+ "n_eligible_parents": 683,
131
+ "k_star_sum": 3840,
132
+ "root_quota": 256,
133
+ "n_to_root": 0
134
+ },
135
+ {
136
+ "layer": 2,
137
+ "n_dead": 7938,
138
+ "n_moved": 7938,
139
+ "n_eligible_parents": 2864,
140
+ "k_star_sum": 11520,
141
+ "root_quota": 768,
142
+ "n_to_root": 61
143
+ },
144
+ {
145
+ "layer": 3,
146
+ "n_dead": 10447,
147
+ "n_moved": 10447,
148
+ "n_eligible_parents": 5786,
149
+ "k_star_sum": 13440,
150
+ "root_quota": 896,
151
+ "n_to_root": 39
152
+ }
153
+ ]
154
+ },
155
+ {
156
+ "kind": "realloc",
157
+ "step": 29000,
158
+ "tokens_seen": 118784000,
159
+ "layers": [
160
+ {
161
+ "layer": 1,
162
+ "n_dead": 13,
163
+ "n_moved": 13,
164
+ "n_eligible_parents": 907,
165
+ "k_star_sum": 3840,
166
+ "root_quota": 256,
167
+ "n_to_root": 0
168
+ },
169
+ {
170
+ "layer": 2,
171
+ "n_dead": 6640,
172
+ "n_moved": 6640,
173
+ "n_eligible_parents": 3698,
174
+ "k_star_sum": 11520,
175
+ "root_quota": 768,
176
+ "n_to_root": 15
177
+ },
178
+ {
179
+ "layer": 3,
180
+ "n_dead": 9206,
181
+ "n_moved": 9206,
182
+ "n_eligible_parents": 7401,
183
+ "k_star_sum": 13440,
184
+ "root_quota": 896,
185
+ "n_to_root": 8
186
+ }
187
+ ]
188
+ },
189
+ {
190
+ "kind": "realloc",
191
+ "step": 39000,
192
+ "tokens_seen": 159744000,
193
+ "layers": [
194
+ {
195
+ "layer": 1,
196
+ "n_dead": 3,
197
+ "n_moved": 3,
198
+ "n_eligible_parents": 1085,
199
+ "k_star_sum": 3840,
200
+ "root_quota": 256,
201
+ "n_to_root": 0
202
+ },
203
+ {
204
+ "layer": 2,
205
+ "n_dead": 5618,
206
+ "n_moved": 5618,
207
+ "n_eligible_parents": 4315,
208
+ "k_star_sum": 11520,
209
+ "root_quota": 768,
210
+ "n_to_root": 1
211
+ },
212
+ {
213
+ "layer": 3,
214
+ "n_dead": 8138,
215
+ "n_moved": 8138,
216
+ "n_eligible_parents": 8605,
217
+ "k_star_sum": 13440,
218
+ "root_quota": 896,
219
+ "n_to_root": 2
220
+ }
221
+ ]
222
+ },
223
+ {
224
+ "kind": "realloc",
225
+ "step": 49000,
226
+ "tokens_seen": 200704000,
227
+ "layers": [
228
+ {
229
+ "layer": 1,
230
+ "n_dead": 3,
231
+ "n_moved": 3,
232
+ "n_eligible_parents": 1260,
233
+ "k_star_sum": 3840,
234
+ "root_quota": 256,
235
+ "n_to_root": 0
236
+ },
237
+ {
238
+ "layer": 2,
239
+ "n_dead": 4782,
240
+ "n_moved": 4782,
241
+ "n_eligible_parents": 4736,
242
+ "k_star_sum": 11520,
243
+ "root_quota": 768,
244
+ "n_to_root": 0
245
+ },
246
+ {
247
+ "layer": 3,
248
+ "n_dead": 7137,
249
+ "n_moved": 7137,
250
+ "n_eligible_parents": 9502,
251
+ "k_star_sum": 13440,
252
+ "root_quota": 896,
253
+ "n_to_root": 1
254
+ }
255
+ ]
256
+ },
257
+ {
258
+ "kind": "realloc",
259
+ "step": 59000,
260
+ "tokens_seen": 241664000,
261
+ "layers": [
262
+ {
263
+ "layer": 1,
264
+ "n_dead": 0,
265
+ "n_moved": 0,
266
+ "n_eligible_parents": 1416,
267
+ "k_star_sum": 3840,
268
+ "root_quota": 256,
269
+ "n_to_root": 0
270
+ },
271
+ {
272
+ "layer": 2,
273
+ "n_dead": 4065,
274
+ "n_moved": 4065,
275
+ "n_eligible_parents": 5069,
276
+ "k_star_sum": 11520,
277
+ "root_quota": 768,
278
+ "n_to_root": 0
279
+ },
280
+ {
281
+ "layer": 3,
282
+ "n_dead": 6273,
283
+ "n_moved": 6273,
284
+ "n_eligible_parents": 10241,
285
+ "k_star_sum": 13440,
286
+ "root_quota": 896,
287
+ "n_to_root": 0
288
+ }
289
+ ]
290
+ },
291
+ {
292
+ "kind": "dead_to_root",
293
+ "step": 61035,
294
+ "tokens_seen": 249999360,
295
+ "n_moved": 9270
296
+ },
297
+ {
298
+ "kind": "realloc",
299
+ "step": 69000,
300
+ "tokens_seen": 282624000,
301
+ "layers": [
302
+ {
303
+ "layer": 1,
304
+ "n_dead": 0,
305
+ "n_moved": 0,
306
+ "n_eligible_parents": 1570,
307
+ "k_star_sum": 3840,
308
+ "root_quota": 256,
309
+ "n_to_root": 0
310
+ },
311
+ {
312
+ "layer": 2,
313
+ "n_dead": 253,
314
+ "n_moved": 253,
315
+ "n_eligible_parents": 5319,
316
+ "k_star_sum": 11520,
317
+ "root_quota": 768,
318
+ "n_to_root": 0
319
+ },
320
+ {
321
+ "layer": 3,
322
+ "n_dead": 1077,
323
+ "n_moved": 1077,
324
+ "n_eligible_parents": 11514,
325
+ "k_star_sum": 13440,
326
+ "root_quota": 896,
327
+ "n_to_root": 0
328
+ }
329
+ ]
330
+ },
331
+ {
332
+ "kind": "realloc",
333
+ "step": 79000,
334
+ "tokens_seen": 323584000,
335
+ "layers": [
336
+ {
337
+ "layer": 1,
338
+ "n_dead": 1,
339
+ "n_moved": 1,
340
+ "n_eligible_parents": 1710,
341
+ "k_star_sum": 3840,
342
+ "root_quota": 256,
343
+ "n_to_root": 0
344
+ },
345
+ {
346
+ "layer": 2,
347
+ "n_dead": 346,
348
+ "n_moved": 346,
349
+ "n_eligible_parents": 5486,
350
+ "k_star_sum": 11520,
351
+ "root_quota": 768,
352
+ "n_to_root": 0
353
+ },
354
+ {
355
+ "layer": 3,
356
+ "n_dead": 1275,
357
+ "n_moved": 1275,
358
+ "n_eligible_parents": 12782,
359
+ "k_star_sum": 13440,
360
+ "root_quota": 896,
361
+ "n_to_root": 0
362
+ }
363
+ ]
364
+ },
365
+ {
366
+ "kind": "realloc",
367
+ "step": 89000,
368
+ "tokens_seen": 364544000,
369
+ "layers": [
370
+ {
371
+ "layer": 1,
372
+ "n_dead": 0,
373
+ "n_moved": 0,
374
+ "n_eligible_parents": 1826,
375
+ "k_star_sum": 3840,
376
+ "root_quota": 256,
377
+ "n_to_root": 0
378
+ },
379
+ {
380
+ "layer": 2,
381
+ "n_dead": 805,
382
+ "n_moved": 805,
383
+ "n_eligible_parents": 5630,
384
+ "k_star_sum": 11520,
385
+ "root_quota": 768,
386
+ "n_to_root": 0
387
+ },
388
+ {
389
+ "layer": 3,
390
+ "n_dead": 1351,
391
+ "n_moved": 1351,
392
+ "n_eligible_parents": 13388,
393
+ "k_star_sum": 13440,
394
+ "root_quota": 896,
395
+ "n_to_root": 0
396
+ }
397
+ ]
398
+ },
399
+ {
400
+ "kind": "realloc",
401
+ "step": 99000,
402
+ "tokens_seen": 405504000,
403
+ "layers": [
404
+ {
405
+ "layer": 1,
406
+ "n_dead": 1,
407
+ "n_moved": 1,
408
+ "n_eligible_parents": 1912,
409
+ "k_star_sum": 3840,
410
+ "root_quota": 256,
411
+ "n_to_root": 0
412
+ },
413
+ {
414
+ "layer": 2,
415
+ "n_dead": 826,
416
+ "n_moved": 826,
417
+ "n_eligible_parents": 5731,
418
+ "k_star_sum": 11520,
419
+ "root_quota": 768,
420
+ "n_to_root": 0
421
+ },
422
+ {
423
+ "layer": 3,
424
+ "n_dead": 1432,
425
+ "n_moved": 1432,
426
+ "n_eligible_parents": 13768,
427
+ "k_star_sum": 13440,
428
+ "root_quota": 896,
429
+ "n_to_root": 0
430
+ }
431
+ ]
432
+ },
433
+ {
434
+ "kind": "realloc",
435
+ "step": 109000,
436
+ "tokens_seen": 446464000,
437
+ "layers": [
438
+ {
439
+ "layer": 1,
440
+ "n_dead": 1,
441
+ "n_moved": 1,
442
+ "n_eligible_parents": 1962,
443
+ "k_star_sum": 3840,
444
+ "root_quota": 256,
445
+ "n_to_root": 0
446
+ },
447
+ {
448
+ "layer": 2,
449
+ "n_dead": 873,
450
+ "n_moved": 873,
451
+ "n_eligible_parents": 5796,
452
+ "k_star_sum": 11520,
453
+ "root_quota": 768,
454
+ "n_to_root": 0
455
+ },
456
+ {
457
+ "layer": 3,
458
+ "n_dead": 1432,
459
+ "n_moved": 1432,
460
+ "n_eligible_parents": 14020,
461
+ "k_star_sum": 13440,
462
+ "root_quota": 896,
463
+ "n_to_root": 0
464
+ }
465
+ ]
466
+ },
467
+ {
468
+ "kind": "realloc",
469
+ "step": 119000,
470
+ "tokens_seen": 487424000,
471
+ "layers": [
472
+ {
473
+ "layer": 1,
474
+ "n_dead": 0,
475
+ "n_moved": 0,
476
+ "n_eligible_parents": 1991,
477
+ "k_star_sum": 3840,
478
+ "root_quota": 256,
479
+ "n_to_root": 0
480
+ },
481
+ {
482
+ "layer": 2,
483
+ "n_dead": 894,
484
+ "n_moved": 894,
485
+ "n_eligible_parents": 5825,
486
+ "k_star_sum": 11520,
487
+ "root_quota": 768,
488
+ "n_to_root": 0
489
+ },
490
+ {
491
+ "layer": 3,
492
+ "n_dead": 1413,
493
+ "n_moved": 1413,
494
+ "n_eligible_parents": 14136,
495
+ "k_star_sum": 13440,
496
+ "root_quota": 896,
497
+ "n_to_root": 0
498
+ }
499
+ ]
500
+ }
501
+ ]
502
+ }
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/export/weights.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be05f1bd5973d2169788d604f6d28839706fad227c78e2a01cd68828bc88caac
3
+ size 603989232
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/interface.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interface every trainable hierarchy SAE implements for ``driver.py``.
2
+
3
+ The driver owns: the activation stream (twin recipe: 500M tokens of the
4
+ twin's corpus, batches of 4096 tokens, Gemma-2-2b layer 12), step counting,
5
+ checkpoint/resume on the Modal volume, metric logging, and the final export.
6
+ Everything architecture-specific — losses, optimizer, LR schedule, decoder
7
+ renormalisation, hierarchy updates, reallocation, dead-feature handling —
8
+ lives inside ``step``.
9
+
10
+ Exports are consumed by the benchmark through :class:`ExportedSAE`: a single
11
+ concatenated latent index space (all levels / layers / experts flattened),
12
+ ``encode(x) -> (batch, n_latents)`` non-negative activations, and the
13
+ architecture's own ancestor claims ``native_ancestors()`` as
14
+ ``{child_index: {ancestor_indices}}`` (direct parents; the benchmark applies
15
+ transitive closure).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+ from typing import Any, Protocol
22
+
23
+ import torch
24
+
25
+
26
+ class HierarchyTrainer(Protocol):
27
+ d_in: int
28
+ n_latents: int # size of the flattened latent index space
29
+
30
+ def step(self, x: torch.Tensor, step: int, total_steps: int) -> dict[str, float]:
31
+ """One optimizer step on a ``(batch, d_in)`` float32 CUDA batch.
32
+
33
+ Returns scalar metrics (must include ``"loss"`` and ``"l0"``, where
34
+ ``l0`` is the mean number of active latents per token across the
35
+ whole flattened index space).
36
+ """
37
+ ...
38
+
39
+ def state_dict(self) -> dict[str, Any]: ...
40
+
41
+ def load_state_dict(self, state: dict[str, Any]) -> None: ...
42
+
43
+ def export(self, out_dir: Path) -> None:
44
+ """Write everything :class:`ExportedSAE` needs to ``out_dir``."""
45
+ ...
46
+
47
+
48
+ class ExportedSAE(Protocol):
49
+ n_latents: int
50
+ W_dec: torch.Tensor # (n_latents, d_in) decoder directions (for cosine baselines)
51
+
52
+ @torch.no_grad()
53
+ def encode(self, x: torch.Tensor) -> torch.Tensor: ...
54
+
55
+ def native_ancestors(self) -> dict[int, set[int]]: ...
56
+
57
+ def latent_level(self) -> list[int]:
58
+ """Level / layer / expert-vs-child tag per flattened latent (for reporting)."""
59
+ ...
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/log.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/model.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tree SAE trainer for Gemma-2-2b layer 12 (``driver.py --arch tree_sae``).
2
+
3
+ Clean-room port of Cao et al., "Tree SAE: Learning Hierarchical Feature
4
+ Structures in Sparse Autoencoders" (arXiv:2605.07922) to the benchmark's
5
+ ``HierarchyTrainer`` / ``ExportedSAE`` interface (``base.py``). Starting point
6
+ was Kirill's synthetic-scale implementation
7
+ (``synth_sae_bench_baseline/.../tree_sae/``); every interpretation of the
8
+ paper and every deviation from that implementation is listed in
9
+ ``TREE_SAE_DECISIONS.md`` next to this file.
10
+
11
+ Architecture (one shared dictionary, layer-major feature ids):
12
+
13
+ - ``pre = (x - b) @ W_enc``; ``relu = ReLU(pre)``; independent TopK inside each
14
+ privilege layer's slice (``layer_ks``); recursive parent gate (paper Eq. 6)
15
+ applied AFTER TopK: ``f*_i = f_i * 1[f*_parent(i) > 0]`` (root-attached
16
+ features are ungated);
17
+ - cumulative reconstructions ``xhat_{<=l} = b + sum_{t<=l} gated_t @ W_dec_t``
18
+ (bias added once); loss ``sum_l ||xhat_{<=l} - x||^2`` (Eq. 7, batch mean);
19
+ - per-layer TopK-style auxiliary dead-feature loss (Eq. 8) on the DETACHED
20
+ residual, aux-k 256, alpha_l = 1/128 for all layers (paper's Gemma setting);
21
+ - dynamic allocation (Alg. 1-2): capacity = running sum of the per-example
22
+ primary loss over examples the feature fires on; parent eligibility >= 1
23
+ firing per 50k tokens; dead = no final activation in 10M tokens;
24
+ reallocation events after 3000 steps then interval x2 capped at 10000;
25
+ optional root child quota (paper's Gemma option); all remaining dead
26
+ features moved to ROOT at half the token budget.
27
+
28
+ Flattened latent index = feature index; ``ROOT = -1`` in the allocation
29
+ vector means "no learned parent". Invariant: ``allocation[i] == ROOT`` or
30
+ ``allocation[i] < layer_start(layer_of(i))`` (parent strictly earlier layer).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import contextlib
36
+ import heapq
37
+ import json
38
+ from dataclasses import asdict, dataclass, fields
39
+ from pathlib import Path
40
+ from typing import Any
41
+
42
+ import torch
43
+
44
+ ROOT = -1
45
+ _TUPLE_FIELDS = {"layer_widths", "layer_ks", "aux_alphas", "adam_betas"}
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class TreeSAEConfig:
50
+ d_in: int = 2304
51
+ # Paper 4-layer ratio [1536:3072:9216:10752] scaled to 32768 (twin width).
52
+ layer_widths: tuple[int, ...] = (2048, 4096, 12288, 14336)
53
+ # Paper 4-layer L0=80 row [56, 11, 7, 6] scaled proportionally to 150.
54
+ layer_ks: tuple[int, ...] = (105, 21, 13, 11)
55
+ aux_k: int = 256
56
+ # Paper App. C: alpha_{1,2,3,4} = 1/128 "on other models such as Gemma-2-2b".
57
+ aux_alphas: tuple[float, ...] = (1.0 / 128.0,) * 4
58
+ # Paper App. G Gemma option: a required number of ROOT children per layer,
59
+ # here a fraction of the layer width at every reallocation event; 0 disables.
60
+ root_child_quota_frac: float = 1.0 / 16.0
61
+ lr: float = 1e-4
62
+ adam_betas: tuple[float, float] = (0.9, 0.999)
63
+ adam_eps: float = 1e-8
64
+ dead_token_window: int = 10_000_000
65
+ parent_eligibility_rate: float = 1.0 / 50_000.0
66
+ realloc_first_interval: int = 3000
67
+ realloc_growth: int = 2
68
+ realloc_cap: int = 10_000
69
+ dead_to_root_frac: float = 0.5 # fraction of total_steps for the dead-to-root event
70
+ seed: int = 0
71
+ autocast_bf16: bool = True # bf16 autocast on CUDA (fp32 master weights / Adam state)
72
+ # False (default, ledger #4): per-layer TopK on raw ReLU pre-activations, THEN the parent
73
+ # gate (realized per-layer L0 <= k). True: gate first, TopK among gate-allowed features
74
+ # (realized L0 == k whenever enough allowed features are positive).
75
+ gate_before_topk: bool = False
76
+
77
+ def __post_init__(self) -> None:
78
+ if not (len(self.layer_widths) == len(self.layer_ks) == len(self.aux_alphas)):
79
+ raise ValueError("layer_widths, layer_ks and aux_alphas must have equal length")
80
+ if any(k > w or k < 1 for k, w in zip(self.layer_ks, self.layer_widths, strict=True)):
81
+ raise ValueError("per-layer k must be in [1, layer width]")
82
+ if not 0.0 <= self.root_child_quota_frac < 1.0:
83
+ raise ValueError("root_child_quota_frac must be in [0, 1)")
84
+
85
+ @property
86
+ def n_layers(self) -> int:
87
+ return len(self.layer_widths)
88
+
89
+ @property
90
+ def n_features(self) -> int:
91
+ return sum(self.layer_widths)
92
+
93
+ def layer_starts(self) -> tuple[int, ...]:
94
+ starts = [0]
95
+ for w in self.layer_widths[:-1]:
96
+ starts.append(starts[-1] + w)
97
+ return tuple(starts)
98
+
99
+ def layer_slices(self) -> tuple[slice, ...]:
100
+ return tuple(slice(s, s + w) for s, w in zip(self.layer_starts(), self.layer_widths, strict=True))
101
+
102
+ def root_quota(self, layer: int) -> int:
103
+ if layer == 0:
104
+ return self.layer_widths[0]
105
+ return int(self.root_child_quota_frac * self.layer_widths[layer])
106
+
107
+ def to_dict(self) -> dict[str, Any]:
108
+ return asdict(self)
109
+
110
+ @classmethod
111
+ def from_dict(cls, d: dict[str, Any]) -> TreeSAEConfig:
112
+ known = {f.name for f in fields(cls)}
113
+ unknown = set(d) - known
114
+ if unknown:
115
+ raise ValueError(f"unknown TreeSAEConfig keys: {sorted(unknown)}")
116
+ fixed = {k: (tuple(v) if k in _TUPLE_FIELDS else v) for k, v in d.items()}
117
+ return cls(**fixed)
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Functional core (shared by trainer and exported model)
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ def layer_index_vector(cfg: TreeSAEConfig) -> torch.Tensor:
126
+ """(n,) int64: privilege layer of every feature."""
127
+ return torch.repeat_interleave(
128
+ torch.arange(cfg.n_layers), torch.tensor(cfg.layer_widths, dtype=torch.long)
129
+ )
130
+
131
+
132
+ def verify_allocation(cfg: TreeSAEConfig, allocation: torch.Tensor) -> None:
133
+ starts = torch.tensor(cfg.layer_starts(), dtype=torch.long, device=allocation.device)
134
+ start_of = starts[layer_index_vector(cfg).to(allocation.device)]
135
+ ok = (allocation == ROOT) | ((allocation >= 0) & (allocation < start_of))
136
+ if not bool(ok.all()):
137
+ raise AssertionError("allocation invariant violated: parent not in a strictly earlier layer")
138
+ if not bool((allocation[cfg.layer_slices()[0]] == ROOT).all()):
139
+ raise AssertionError("first-layer features must be ROOT-attached")
140
+
141
+
142
+ def firing_mask(cfg: TreeSAEConfig, relu: torch.Tensor, allocation: torch.Tensor) -> torch.Tensor:
143
+ """(B, n) bool: per-layer TopK selection AND recursive parent gate (Eq. 6).
144
+
145
+ Default (ledger reading): TopK on the raw pre-activations first, gate second.
146
+ With ``cfg.gate_before_topk`` the TopK runs on the gated candidates instead.
147
+ Layers are processed in ascending order, so every parent's final firing state
148
+ is known when its children are gated. No gradient flows through the mask.
149
+ """
150
+ with torch.no_grad():
151
+ fires = torch.zeros_like(relu, dtype=torch.bool)
152
+ positive = relu > 0
153
+ for layer, (sl, k) in enumerate(zip(cfg.layer_slices(), cfg.layer_ks, strict=True)):
154
+ allowed = None
155
+ if layer > 0:
156
+ parents = allocation[sl]
157
+ is_root = parents == ROOT
158
+ if not bool(is_root.all()):
159
+ allowed = is_root.unsqueeze(0) | fires[:, parents.clamp(min=0)]
160
+ cand = relu[:, sl]
161
+ if allowed is not None and cfg.gate_before_topk:
162
+ cand = cand * allowed
163
+ _, idx = cand.topk(k, dim=1)
164
+ fires[:, sl].scatter_(1, idx, True)
165
+ fires[:, sl] &= positive[:, sl]
166
+ if allowed is not None:
167
+ fires[:, sl] &= allowed
168
+ return fires
169
+
170
+
171
+ def cumulative_reconstructions(
172
+ cfg: TreeSAEConfig, gated: torch.Tensor, W_dec: torch.Tensor, b: torch.Tensor
173
+ ) -> list[torch.Tensor]:
174
+ """``xhat_{<=l} = b + sum_{t<=l} gated_t @ W_dec_t`` for every layer l."""
175
+ out: list[torch.Tensor] = []
176
+ running = b.unsqueeze(0)
177
+ for sl in cfg.layer_slices():
178
+ running = running + gated[:, sl] @ W_dec[sl]
179
+ out.append(running)
180
+ return out
181
+
182
+
183
+ def greedy_optimal_counts(capacities: list[float], eligible: list[bool], n_children: int) -> list[int]:
184
+ """Paper Algorithm 1 (heap greedy max-min payoff). Ties -> smaller id."""
185
+ m = len(capacities)
186
+ k_star = [0] * m
187
+ heap = [(-capacities[p], p) for p in range(m) if eligible[p]]
188
+ if not heap or n_children <= 0:
189
+ return k_star
190
+ heapq.heapify(heap)
191
+ assigned = 0
192
+ while heap and assigned < n_children:
193
+ _, p = heapq.heappop(heap)
194
+ k_star[p] += 1
195
+ heapq.heappush(heap, (-capacities[p] / (k_star[p] + 1), p))
196
+ assigned += 1
197
+ return k_star
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # Trainer
202
+ # ---------------------------------------------------------------------------
203
+
204
+
205
+ class TreeSAETrainer:
206
+ def __init__(self, cfg: TreeSAEConfig, device: str | torch.device = "cuda") -> None:
207
+ self.cfg = cfg
208
+ self.device = torch.device(device)
209
+ self.d_in = cfg.d_in
210
+ self.n_latents = cfg.n_features
211
+ self.gen = torch.Generator(device="cpu").manual_seed(cfg.seed)
212
+ n, d = cfg.n_features, cfg.d_in
213
+
214
+ # kaiming-uniform bound for fan_in=d (a=0): sqrt(6/d); rows unit-norm; tied encoder.
215
+ w_dec = torch.empty(n, d, dtype=torch.float32).uniform_(-((6.0 / d) ** 0.5), (6.0 / d) ** 0.5, generator=self.gen)
216
+ w_dec /= w_dec.norm(dim=1, keepdim=True)
217
+ self.W_dec = torch.nn.Parameter(w_dec.to(self.device))
218
+ self.W_enc = torch.nn.Parameter(w_dec.T.contiguous().to(self.device))
219
+ self.b = torch.nn.Parameter(torch.zeros(d, dtype=torch.float32, device=self.device))
220
+ self.optimizer = torch.optim.Adam(
221
+ [self.W_enc, self.W_dec, self.b], lr=cfg.lr, betas=cfg.adam_betas, eps=cfg.adam_eps
222
+ )
223
+
224
+ # Allocation state (all on device, vectorised per-step bookkeeping).
225
+ alloc = torch.full((n,), ROOT, dtype=torch.long)
226
+ for sl in cfg.layer_slices()[1:]:
227
+ alloc[sl] = torch.randint(0, sl.start, (sl.stop - sl.start,), generator=self.gen)
228
+ self.allocation = alloc.to(self.device)
229
+ self.capacity = torch.zeros(n, dtype=torch.float64, device=self.device)
230
+ self.fire_count = torch.zeros(n, dtype=torch.long, device=self.device)
231
+ self.last_fire = torch.full((n,), -1, dtype=torch.long, device=self.device)
232
+ self.tokens_seen = 0
233
+ self.step_count = 0
234
+ self.realloc_interval = cfg.realloc_first_interval
235
+ self.next_realloc_step = cfg.realloc_first_interval
236
+ self.dead_to_root_done = False
237
+ self.events: list[dict[str, Any]] = []
238
+
239
+ self._layer_index = layer_index_vector(cfg).to(self.device)
240
+ self._first_layer = self._layer_index == 0
241
+ self._use_autocast = bool(cfg.autocast_bf16) and self.device.type == "cuda"
242
+ verify_allocation(cfg, self.allocation)
243
+
244
+ # ------------------------------------------------------------------ misc
245
+ def config_dict(self) -> dict[str, Any]:
246
+ return {**self.cfg.to_dict(), "n_latents": self.n_latents, "layer_starts": list(self.cfg.layer_starts())}
247
+
248
+ def _autocast(self):
249
+ if self._use_autocast:
250
+ return torch.autocast("cuda", dtype=torch.bfloat16)
251
+ return contextlib.nullcontext()
252
+
253
+ # ------------------------------------------------------------ statistics
254
+ def dead_mask(self) -> torch.Tensor:
255
+ """(n,) bool: no positive final activation in the last ``dead_token_window`` tokens."""
256
+ if self.tokens_seen < self.cfg.dead_token_window:
257
+ return torch.zeros(self.n_latents, dtype=torch.bool, device=self.device)
258
+ return (self.tokens_seen - self.last_fire) >= self.cfg.dead_token_window
259
+
260
+ def eligible_parent_mask(self) -> torch.Tensor:
261
+ """(n,) bool: firing rate >= parent_eligibility_rate (running, from start)."""
262
+ if self.tokens_seen == 0:
263
+ return torch.zeros(self.n_latents, dtype=torch.bool, device=self.device)
264
+ return self.fire_count.double() / float(self.tokens_seen) >= self.cfg.parent_eligibility_rate
265
+
266
+ # --------------------------------------------------------------- forward
267
+ def _forward(self, x: torch.Tensor):
268
+ """Returns (relu, fires, cumulative, per_example_loss)."""
269
+ with self._autocast():
270
+ relu = torch.relu((x - self.b) @ self.W_enc)
271
+ fires = firing_mask(self.cfg, relu, self.allocation)
272
+ gated = relu * fires
273
+ cumulative = cumulative_reconstructions(self.cfg, gated, self.W_dec, self.b)
274
+ per_example = torch.stack([((c.float() - x) ** 2).sum(dim=1) for c in cumulative], dim=0).sum(dim=0)
275
+ return relu, fires, cumulative, per_example
276
+
277
+ def _aux_loss(self, x: torch.Tensor, relu: torch.Tensor, cumulative: list[torch.Tensor], dead: torch.Tensor) -> torch.Tensor:
278
+ """Per-layer TopK-style aux loss (Eq. 8): top aux_k dead features of layer l (by
279
+ ungated ReLU pre-activation) reconstruct the detached residual x - xhat_{<=l}."""
280
+ total = x.new_zeros(())
281
+ for l, (sl, alpha) in enumerate(zip(self.cfg.layer_slices(), self.cfg.aux_alphas, strict=True)):
282
+ if alpha == 0.0:
283
+ continue
284
+ dead_ids = torch.nonzero(dead[sl], as_tuple=True)[0] + sl.start
285
+ n_dead = int(dead_ids.numel())
286
+ if n_dead == 0:
287
+ continue
288
+ with self._autocast():
289
+ dead_acts = relu[:, dead_ids]
290
+ vals, idx = dead_acts.topk(min(self.cfg.aux_k, n_dead), dim=1)
291
+ picked = torch.zeros_like(dead_acts).scatter_(1, idx, vals)
292
+ e_hat = picked @ self.W_dec[dead_ids]
293
+ resid = (x - cumulative[l].float()).detach()
294
+ total = total + alpha * ((e_hat.float() - resid) ** 2).sum(dim=1).mean()
295
+ return total
296
+
297
+ @torch.no_grad()
298
+ def encode(self, x: torch.Tensor) -> torch.Tensor:
299
+ """Final gated activations (fp32, no autocast) for raw residual activations."""
300
+ x = x.to(self.device, torch.float32)
301
+ relu = torch.relu((x - self.b) @ self.W_enc)
302
+ return relu * firing_mask(self.cfg, relu, self.allocation)
303
+
304
+ # ------------------------------------------------------------------ step
305
+ def step(self, x: torch.Tensor, step: int, total_steps: int) -> dict[str, float]:
306
+ cfg = self.cfg
307
+ x = x.to(self.device, torch.float32)
308
+ B = x.shape[0]
309
+ dead = self.dead_mask()
310
+
311
+ relu, fires, cumulative, per_example = self._forward(x)
312
+ recon_loss = per_example.mean()
313
+ aux_loss = self._aux_loss(x, relu, cumulative, dead)
314
+ loss = recon_loss + aux_loss
315
+
316
+ self.optimizer.zero_grad(set_to_none=True)
317
+ loss.backward()
318
+ self._project_decoder_grads()
319
+ self.optimizer.step()
320
+ self._renormalize_decoder()
321
+
322
+ with torch.no_grad():
323
+ per_feature = fires.sum(dim=0) # (n,) int64
324
+ inc = per_example.detach() @ fires.to(torch.float32) # (n,) fp32 batch increment
325
+ self.capacity += inc.double()
326
+ self.fire_count += per_feature
327
+ fired = per_feature > 0
328
+ self.last_fire = torch.where(fired, torch.full_like(self.last_fire, self.tokens_seen + B), self.last_fire)
329
+ self.tokens_seen += B
330
+ self.step_count = step + 1
331
+
332
+ n_dead = dead.sum()
333
+ n_root = (self.allocation == ROOT).sum() - int(cfg.layer_widths[0])
334
+ layer_l0 = torch.stack([per_feature[sl].sum() for sl in cfg.layer_slices()]).double() / B
335
+ mse = ((cumulative[-1].float() - x) ** 2).mean()
336
+ scalars = torch.stack([
337
+ loss.detach().double(), recon_loss.detach().double(), aux_loss.detach().double(),
338
+ mse.double(), n_dead.double(), n_root.double(), per_feature.sum().double() / B,
339
+ ]).tolist()
340
+ layer_l0 = layer_l0.tolist()
341
+
342
+ # --- allocation events (post-step, 1-based step count) ---
343
+ count = step + 1
344
+ if count == self.next_realloc_step:
345
+ self.reallocate()
346
+ self.realloc_interval = min(self.realloc_interval * cfg.realloc_growth, cfg.realloc_cap)
347
+ self.next_realloc_step = count + self.realloc_interval
348
+ if not self.dead_to_root_done and count >= int(cfg.dead_to_root_frac * total_steps):
349
+ self.move_dead_to_root()
350
+
351
+ metrics = {
352
+ "loss": scalars[0], "recon_loss": scalars[1], "aux_loss": scalars[2], "mse": scalars[3],
353
+ "n_dead": scalars[4], "frac_dead": scalars[4] / self.n_latents,
354
+ "n_root_attached": scalars[5], "l0": scalars[6],
355
+ "n_realloc_events": float(sum(e["kind"] == "realloc" for e in self.events)),
356
+ "dead_to_root_done": float(self.dead_to_root_done),
357
+ }
358
+ for l, v in enumerate(layer_l0):
359
+ metrics[f"l0_layer{l}"] = v
360
+ return metrics
361
+
362
+ @torch.no_grad()
363
+ def _project_decoder_grads(self) -> None:
364
+ g = self.W_dec.grad
365
+ if g is None:
366
+ return
367
+ rows = self.W_dec / self.W_dec.norm(dim=1, keepdim=True)
368
+ g -= (g * rows).sum(dim=1, keepdim=True) * rows
369
+
370
+ @torch.no_grad()
371
+ def _renormalize_decoder(self) -> None:
372
+ self.W_dec.data /= self.W_dec.data.norm(dim=1, keepdim=True)
373
+
374
+ # ------------------------------------------------------------ allocation
375
+ @torch.no_grad()
376
+ def reallocate(self) -> dict[str, Any]:
377
+ """One reallocation event (Alg. 2): per layer compute k* (Alg. 1) over all earlier
378
+ features, then first-fit the layer's DEAD children into parents whose live-child
379
+ count is below k* (ROOT quota slots first, then eligible parents in ascending id).
380
+ Live edges are never modified; unplaceable dead children keep their parent."""
381
+ cfg = self.cfg
382
+ dead = self.dead_mask().cpu()
383
+ eligible = self.eligible_parent_mask().cpu()
384
+ cap = self.capacity.cpu()
385
+ alloc = self.allocation.cpu().clone()
386
+ event: dict[str, Any] = {"kind": "realloc", "step": self.step_count, "tokens_seen": self.tokens_seen, "layers": []}
387
+ for layer, sl in enumerate(cfg.layer_slices()):
388
+ if layer == 0:
389
+ continue
390
+ m, width = sl.start, sl.stop - sl.start
391
+ quota = cfg.root_quota(layer)
392
+ k_star = torch.tensor(
393
+ greedy_optimal_counts(cap[:m].tolist(), eligible[:m].tolist(), width - quota), dtype=torch.long
394
+ )
395
+ children, child_dead = alloc[sl], dead[sl]
396
+ live_learned = children[(children != ROOT) & ~child_dead]
397
+ live_counts = torch.bincount(live_learned, minlength=m)
398
+ live_root = int(((children == ROOT) & ~child_dead).sum())
399
+ deficit = (k_star - live_counts).clamp(min=0) * eligible[:m].long()
400
+ parent_seq = torch.cat([
401
+ torch.full((max(quota - live_root, 0),), ROOT, dtype=torch.long),
402
+ torch.repeat_interleave(torch.arange(m), deficit),
403
+ ])
404
+ dead_children = torch.nonzero(child_dead, as_tuple=True)[0] + sl.start # ascending ids
405
+ n_assign = min(int(dead_children.numel()), int(parent_seq.numel()))
406
+ if n_assign > 0:
407
+ alloc[dead_children[:n_assign]] = parent_seq[:n_assign]
408
+ event["layers"].append({
409
+ "layer": layer, "n_dead": int(dead_children.numel()), "n_moved": n_assign,
410
+ "n_eligible_parents": int(eligible[:m].sum()), "k_star_sum": int(k_star.sum()),
411
+ "root_quota": quota, "n_to_root": int((parent_seq[:n_assign] == ROOT).sum()),
412
+ })
413
+ verify_allocation(cfg, alloc)
414
+ self.allocation = alloc.to(self.device)
415
+ self.events.append(event)
416
+ return event
417
+
418
+ @torch.no_grad()
419
+ def move_dead_to_root(self) -> int:
420
+ movable = self.dead_mask() & ~self._first_layer
421
+ self.allocation = torch.where(movable, torch.full_like(self.allocation, ROOT), self.allocation)
422
+ self.dead_to_root_done = True
423
+ verify_allocation(self.cfg, self.allocation)
424
+ moved = int(movable.sum())
425
+ self.events.append({"kind": "dead_to_root", "step": self.step_count, "tokens_seen": self.tokens_seen, "n_moved": moved})
426
+ return moved
427
+
428
+ # ------------------------------------------------------------ checkpoint
429
+ def state_dict(self) -> dict[str, Any]:
430
+ return {
431
+ "config": self.cfg.to_dict(),
432
+ "model": {"W_enc": self.W_enc.detach().clone(), "W_dec": self.W_dec.detach().clone(), "b": self.b.detach().clone()},
433
+ "optimizer": _clone_tree(self.optimizer.state_dict()),
434
+ "allocation": {
435
+ "allocation": self.allocation.clone(), "capacity": self.capacity.clone(),
436
+ "fire_count": self.fire_count.clone(), "last_fire": self.last_fire.clone(),
437
+ "tokens_seen": self.tokens_seen, "realloc_interval": self.realloc_interval,
438
+ "next_realloc_step": self.next_realloc_step, "dead_to_root_done": self.dead_to_root_done,
439
+ "events": list(self.events),
440
+ },
441
+ "generator": self.gen.get_state().clone(),
442
+ "step": self.step_count,
443
+ }
444
+
445
+ def load_state_dict(self, state: dict[str, Any]) -> None:
446
+ with torch.no_grad():
447
+ self.W_enc.copy_(state["model"]["W_enc"])
448
+ self.W_dec.copy_(state["model"]["W_dec"])
449
+ self.b.copy_(state["model"]["b"])
450
+ self.optimizer.load_state_dict(_clone_tree(state["optimizer"]))
451
+ a = state["allocation"]
452
+ self.allocation = a["allocation"].to(self.device, torch.long)
453
+ self.capacity = a["capacity"].to(self.device, torch.float64)
454
+ self.fire_count = a["fire_count"].to(self.device, torch.long)
455
+ self.last_fire = a["last_fire"].to(self.device, torch.long)
456
+ self.tokens_seen = int(a["tokens_seen"])
457
+ self.realloc_interval = int(a["realloc_interval"])
458
+ self.next_realloc_step = int(a["next_realloc_step"])
459
+ self.dead_to_root_done = bool(a["dead_to_root_done"])
460
+ self.events = list(a["events"])
461
+ self.gen.set_state(state["generator"].cpu())
462
+ self.step_count = int(state["step"])
463
+ verify_allocation(self.cfg, self.allocation)
464
+
465
+ # ---------------------------------------------------------------- export
466
+ def export(self, out_dir: Path) -> None:
467
+ from safetensors.torch import save_file
468
+
469
+ out_dir = Path(out_dir)
470
+ out_dir.mkdir(parents=True, exist_ok=True)
471
+ save_file(
472
+ {"W_enc": self.W_enc.detach().cpu().contiguous(), "W_dec": self.W_dec.detach().cpu().contiguous(), "b": self.b.detach().cpu()},
473
+ str(out_dir / "weights.safetensors"),
474
+ )
475
+ dead = self.dead_mask()
476
+ (out_dir / "allocation.json").write_text(json.dumps({
477
+ "parent": self.allocation.cpu().tolist(),
478
+ "layer": self._layer_index.cpu().tolist(),
479
+ "dead": dead.cpu().tolist(),
480
+ }))
481
+ (out_dir / "config.json").write_text(json.dumps({
482
+ "arch": "tree_sae", "config": self.cfg.to_dict(), "n_latents": self.n_latents,
483
+ "layer_starts": list(self.cfg.layer_starts()), "step": self.step_count,
484
+ "tokens_seen": self.tokens_seen, "n_dead": int(dead.sum()),
485
+ "n_root_attached": int((self.allocation == ROOT).sum()) - int(self.cfg.layer_widths[0]),
486
+ "events": self.events,
487
+ }, indent=1))
488
+
489
+
490
+ def _clone_tree(obj: Any) -> Any:
491
+ if isinstance(obj, torch.Tensor):
492
+ return obj.clone()
493
+ if isinstance(obj, dict):
494
+ return {k: _clone_tree(v) for k, v in obj.items()}
495
+ if isinstance(obj, list):
496
+ return [_clone_tree(v) for v in obj]
497
+ if isinstance(obj, tuple):
498
+ return tuple(_clone_tree(v) for v in obj)
499
+ return obj
500
+
501
+
502
+ def build_trainer(d_in: int, overrides: dict, device: str = "cuda") -> TreeSAETrainer:
503
+ cfg = TreeSAEConfig.from_dict({**dict(overrides), "d_in": d_in})
504
+ return TreeSAETrainer(cfg, device=device)
505
+
506
+
507
+ # ---------------------------------------------------------------------------
508
+ # Exported model
509
+ # ---------------------------------------------------------------------------
510
+
511
+
512
+ class ExportedTreeSAE:
513
+ def __init__(self, cfg: TreeSAEConfig, W_enc: torch.Tensor, W_dec: torch.Tensor, b: torch.Tensor, allocation: torch.Tensor, device) -> None:
514
+ self.cfg = cfg
515
+ self.device = torch.device(device)
516
+ self.n_latents = cfg.n_features
517
+ self.W_enc = W_enc.to(self.device, torch.float32)
518
+ self.W_dec = W_dec.to(self.device, torch.float32)
519
+ self.b = b.to(self.device, torch.float32)
520
+ self.allocation = allocation.to(self.device, torch.long)
521
+ verify_allocation(cfg, self.allocation)
522
+
523
+ @torch.no_grad()
524
+ def encode(self, x: torch.Tensor) -> torch.Tensor:
525
+ x = x.to(self.device, torch.float32)
526
+ relu = torch.relu((x - self.b) @ self.W_enc)
527
+ return relu * firing_mask(self.cfg, relu, self.allocation)
528
+
529
+ @torch.no_grad()
530
+ def decode(self, acts: torch.Tensor) -> torch.Tensor:
531
+ return acts.to(self.device, torch.float32) @ self.W_dec + self.b
532
+
533
+ def native_ancestors(self) -> dict[int, set[int]]:
534
+ alloc = self.allocation.cpu().tolist()
535
+ return {child: {parent} for child, parent in enumerate(alloc) if parent != ROOT}
536
+
537
+ def latent_level(self) -> list[int]:
538
+ return layer_index_vector(self.cfg).tolist()
539
+
540
+
541
+ def load_exported(export_dir: Path, device: str = "cuda") -> ExportedTreeSAE:
542
+ from safetensors.torch import load_file
543
+
544
+ export_dir = Path(export_dir)
545
+ meta = json.loads((export_dir / "config.json").read_text())
546
+ cfg = TreeSAEConfig.from_dict(meta["config"])
547
+ weights = load_file(str(export_dir / "weights.safetensors"))
548
+ alloc = torch.tensor(json.loads((export_dir / "allocation.json").read_text())["parent"], dtype=torch.long)
549
+ return ExportedTreeSAE(cfg, weights["W_enc"], weights["W_dec"], weights["b"], alloc, device)
gemma-2-2b/layer-12/tree_sae/tree_sae_32k_k5_seed0/summary.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "run_name": "tree_sae_32k_k5_seed0",
3
+ "arch": "tree_sae",
4
+ "steps": 122070,
5
+ "tokens": 499998720,
6
+ "seconds": 33316.1808950901,
7
+ "export": "/vol/train/tree_sae_32k_k5_seed0/export",
8
+ "group": [
9
+ "hsae_32k_k5_seed0",
10
+ "tree_sae_32k_k5_seed0",
11
+ "hsae_forest_32k_k5_seed0"
12
+ ]
13
+ }