diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..f8d30d0d82ad5bf6475efd9b27fc5ec30327bc13 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +sparsity/figures/sparsity_03_informed_vs_random.png filter=lfs diff=lfs merge=lfs -text +sparsity/figures/sparsity_01_e0_loss_vs_k.png filter=lfs diff=lfs merge=lfs -text +sparsity/figures/sparsity_02_step0_finished_runs.png filter=lfs diff=lfs merge=lfs -text diff --git a/sparsity/code/SPARSITY_PLAN.md b/sparsity/code/SPARSITY_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..a223ba0db219b89b4946c18f04d88591843eedbe --- /dev/null +++ b/sparsity/code/SPARSITY_PLAN.md @@ -0,0 +1,490 @@ +# A program names the keys each head reads, and these experiments measure what that costs + +Written 2026-10-19 from the meeting notes, the slide on the TinyLlama head, Tobias's head-labelling +results on `origin/tobias_dev` (`weekly-updates/10-12-26/README.md`), and the repo's index-mode and +8192-token runs. E1 to E3 were replaced on 2026-10-21 by steps 0 to 2, all on GPT-2 trained from random weights. + +## The notes ask for two experiments + +**Note 1** asks for one figure. The x axis is the number of keys each query reads, called top k. The y +axis is the loss of a model trained with every head restricted to k keys. One line per rule that picks +the k keys: a sliding window plus the first token, the keys a program predicts, and k random keys as +the control. The slide adds a fourth line, the keys the dense model itself scores highest, which is +what DeepSeek's sparse attention trains its indexer to imitate. + +**Note 2** asks which heads are hard for the model to learn and whether the model can be trained +around them. Tobias's long-context heads are the heads whose attention lands far from the query. The +note asks three things about them. First, whether they resemble the task-specific heads of the +automaton. Second, whether a sparse model still trains well when those heads are supplied or kept +dense. Third, which head types the key index must contain, named as induction, first token and the +residual. + +## Three hypotheses, each with the result that would reject it + +**H1, the program is an indexer.** At a fixed k, a model trained with the program's keys reaches a loss +as low as a model trained with the dense model's own top-k keys, and lower than the window and random +rules. Rejected if the program line sits on the window line at every k, which would mean the n-gram +matches add nothing beyond what the window names. + +**H2, the long-range heads set the sparsity bound.** The cost of any k-key rule at long context sits in +the heads whose attention lands beyond the window and on the tokens without an in-context copy. Keeping +those heads dense and indexing the other heads recovers the dense loss. Rejected if keeping any 18 heads +dense recovers the same loss, or if the cost sits in the windowed heads instead. + +**H3, induction keys carry the program's gain.** Of the key families a program can name, the first +token plus the order-1 induction matches account for most of the gap between the window rule and the +oracle rule, and previous-occurrence keys add nothing on top. Rejected if the ladder window, plus +induction, plus occurrence shows no step at induction. + +## What the repo and Tobias's branch have measured so far + +The measurements below bear on the hypotheses and set the baselines. All training numbers are +validation loss on GPT-2 small trained on FineWeb under the track-3 recipe, one seed. The single-run +noise at 1024 tokens is 0.005 nats at step 1000. + +| measurement | where | number | +|---|---|---| +| 18 position heads (sink, previous token, window) as programs, 8192 tokens, 3250 steps | `results/fineweb/f1_pos18_T8192_s0.json` | +0.018 over dense (3.202 against 3.185) | +| the same 18 heads deleted, 8192 tokens | `f1_zeropos18_T8192_s0.json` | +0.014 | +| the same 18 heads as programs, 1024 tokens | `f1_pos18_T1024_s0.json` | +0.019 (3.276 against 3.258) | +| 54 of 72 heads on 64 recent keys plus position 0, weights learned, 1024 tokens, 4500 steps | `f1_index_window64_rest54_l4500_s0.json` | +0.006 | +| 36 heads of layers 0 to 5 on the same 64-key window | `f1_index_window64_l0to5_l4500_s0.json` | +0.011 | +| 18 mid-layer heads on the trained dense model's 8 largest keys, weights learned | `f1_index_teachkeys_sp18_l4500_s0.json` | lead of 0.175 at step 250, +0.022 at 4500 | +| 6 best content heads on order-1 induction keys plus position 0, 600 steps | FINEWEB_PLAN.md, stage P | within 0.006 of dense, no lead | +| step time, 1024 to 16384 tokens, dense | `f1_long_context_timing.json` | +29 percent | +| windowing 36 heads, step time saved at 16384 tokens | same | 6 percent | +| 672 Llama-3.2-3B heads, mean first-token mass on natural text at 1024 tokens | Tobias, atlas | 0.61 | +| heads keeping at least 0.90 of their mass on the first token plus the last 128 keys | Tobias, `sink_window_support.py` | 403 of 672 | +| share of non-sink mass more than 64 tokens back | Tobias, atlas | about one third in every layer group | +| heads at template IoU of at least 0.5 with the sink removed | Tobias, nearest template | 31 of 672 | +| induction heads and previous-occurrence heads at mass 0.3 or more on the repeated-sequence set | Tobias, atlas | 18 and 4 | +| TinyLlama head on the 22-token sentence of the slide, query-key pairs read | slide | dense 253, top 3 reads 63, n-gram rule reads 41 | + +Four readings follow from the table. At 1024 tokens the number of keys matters more than which keys +are named, since 64 recent keys on 54 heads cost 0.006 while the dense model's own 8 keys on 18 heads +cost 0.022. The 8-key oracle starts with a lead of 0.175 and ends as a cost equal to deleting the heads, +so a fixed key set that is right for the trained model is wrong for the model early in training, or 8 +keys are too few for those heads by the end. Programs on the 18 position heads cost the same 0.018 at +8192 tokens as at 1024, so the long window did not change what those heads cost. On Llama-3.2-3B, a +window of 128 keys plus the first token covers 0.90 of the attention of 403 of 672 heads, and the +other 269 heads put a third of their non-sink mass more than 64 tokens back, which is the set note 2 +calls the long-context heads. + +## The heads that are hard to learn, across the three models + +Note 2 asks whether the long-context heads resemble the task-specific heads. The table puts the head +classes of the three models side by side, from `project-standing-2026-10-15`, `t17-attention-types` +and Tobias's labels. + +| class | automaton (TinyLlama, 704 heads) | GPT-2 small on FineWeb (72 heads) | Llama-3.2-3B (672 heads) | +|---|---|---|---| +| position (sink, self, previous token, window) | 144 of Amiri's 176 trivial programs | 18 in layers 0 to 4, learned by step 250 | 9 pure sink, about 7 self, about 15 previous or window 2, 403 at 0.90 coverage by sink plus 128 keys | +| match (induction, previous occurrence) | 7 same-window lookup heads in layer 2, 32 task programs | 5 induction heads in layers 3 to 7, learned by step 150 to 250 | 18 induction, 4 previous occurrence, unambiguous only on the repeated set | +| long-range content, no program fits | layers 2 to 4 (89 heads) and layer 0 (31 heads) | layers 7 to 10, learned from step 1000 on, 0.139 of the teacher lead | the 65-plus tail, a third of non-sink mass, no template at IoU above 0.3 | + +The task-specific heads of the automaton are match heads with a 3-cell window, and the automaton's +hard heads are the content heads of layers 0 and 2 to 4. On language the hard heads are the +long-range content heads, which the key-recall test on GPT-2 found to match none of 7 surface rules. +So the long-context heads and the task-specific heads are different classes, and only the match +class has a program in both settings. E2 tests whether the model can be trained around the content +class. + +## Experiments + +### E0. Perplexity against k on the pretrained Llama-3.2-3B, no training + +This is Tobias's next step 1(b) extended to a k sweep, and it gives the sparsity-versus-perplexity +curve the meeting asked about without a single training run. + +1. I take Tobias's quality harness (`evals/quality/`) and the post-softmax hook in + `llama-3b-pl-kernels/reference/hf_modeling_llama.py`, and add a per-row mask that keeps k keys + per query in every head. +2. I run perplexity on his wiki, math and code sets at 1024 tokens, and on WikiText-2 at 2048 tokens, + for k in 8, 32, 128 and 512, under 5 rules. The rules are the first token plus the k minus 1 most + recent keys; the first token plus order-1 induction matches then recent keys to fill k; the first + token plus previous occurrences of the query token then recent keys; the head's own k largest + scores; and the first token plus k minus 1 random earlier keys. The head's own scores on the kept + keys are renormalised in every rule. +3. For the same rules and k I compute the share of each head's attention mass on the named keys from + Tobias's stored maps, which extends `sink_window_support.py` from windows to the other rules. +4. I read two things. The perplexity against k per rule answers note 1 on a pretrained model. The + per-head coverage against the perplexity rise when only that head is restricted tests whether + coverage predicts cost, which Tobias flagged as untested. + +Cost: one day of code on his branch, and under 2 hours of A100 time, since each setting is a forward +pass over 300 texts. The 318 GB of maps sit on his pod volume, so step 3 runs there. This needs his +agreement to work on `tobias_dev` or a copy of the harness. + +### Plan of 2026-10-21, all on GPT-2 small trained from random weights on FineWeb + +On 2026-10-21 Laura asked to replace E1 to E3 with experiments on the GPT-2 FineWeb model alone, so +that the sparsity result connects to the training runs. E0 and the E1 first results below stay as a +record. The question is how loss trained from random weights rises as the share of query-key pairs +read falls, when the heads to restrict are chosen from the head families of the trained model against +heads chosen at random. + +Two facts from the training runs shape the steps. From random weights a head's index inside its layer +carries no information, by the equivariance proposition of 2026-10-19 and the layers 0 to 2 screen +(matched minus permuted patterns +0.001 over 3 seeds), so an informed choice can only set how many +heads of each layer are restricted. Every readable key rule tried on the content heads did worse than +recency or matched it (stage K, stage P, E1 at k 32), so step 1 keeps one rule, the first token plus +recent keys, and varies which heads use it. + +### Step 0. The finished runs on one sparsity axis, no new runs + +I took every finished FineWeb run trained from random weights in which some heads read fewer keys or +were deleted, and computed the share of the dense model's causal query-key pairs it reads over all 72 +heads. A head on the first token plus k recent keys reads min(i + 1, k) keys at query i, a head on a +program's 8 keys plus the first token reads at most 9 (an upper bound, since a program row can name +fewer), and a deleted head reads none. I plotted that share and the final loss minus the dense run of +the same length and schedule, next to the share of each layer's 6 heads restricted. +`scripts/sparsity_figures.py 02` writes `figures/sparsity/sparsity_02_step0_finished_runs.png`. + +| run | T | heads restricted | keys per query | pairs read, share of dense | loss over dense | +|---|---|---|---|---|---| +| index_amiri18_top8 | 1024 | 25%, Amiri's slots | program's 8 plus first token | 0.754 | +0.004 | +| pos18 | 1024 | 25%, position heads | fixed position programs | 0.754 | +0.019 | +| index_teachkeys_sp18 | 1024 | 25%, layers 3 to 10 | trained model's 8 plus first token | 0.754 | +0.022 | +| random_zero18 | 1024 | 25%, Amiri's slots | deleted | 0.750 | +0.026 | +| index_window64_l0to5 | 1024 | 50%, layers 0 to 5 | first token plus 64 recent | 0.561 | +0.011 | +| index_window64_rest54 | 1024 | 75%, all but 18 in layers 3 to 10 | first token plus 64 recent | 0.342 | +0.006 | +| zeropos18 | 8192 | 25%, position heads | deleted | 0.750 | +0.014 | +| pos18 | 8192 | 25%, position heads | fixed position programs | 0.750 | +0.018 | +| s1_window32 | 8192 | 100% | first token plus 31 recent | 0.008 | +0.239 | + +The 1024-token runs use the 4500-step schedule against dense_l4500_s0 (3.2122), except pos18, which +uses 3250 steps against dense_s0 (3.2575). The 8192-token runs use 3250 steps against dense_T8192_s0 +(3.1845). One seed each; the single-run noise is about 0.005 nats. + +Readings. +- At 1024 tokens the run that reads the fewest pairs (0.342, 75% of heads on 64 recent keys) costs + less than four of the five runs that read 0.75, so the loss cost is set by which layers are restricted. + The 54 heads it restricts leave the 18 heads of layers 3 to 10 dense, and those 18 heads on the + trained model's own 8 keys cost 0.022. +- At 8192 tokens the finished runs leave a gap between a share of 0.75 and a share of 0.008. Step 1 + places points inside that gap. +- The 4 runs at a share near 0.75 span 0.004 to 0.026 nats, which is the size of effect the choice of + heads can have at 25% of heads. + +### Step 1. Informed against random head allocation at 8192 tokens, launched 2026-10-22 + +I train GPT-2 small from random weights at 8192 tokens for 3250 steps, the recipe of dense_T8192_s0, +with 18, 36 or 54 of the 72 heads (25%, 50%, 75%) on the first token plus 31 recent keys, weights +learned, and the other heads dense. The 100% point is s1_window32_T8192_s0, which used the same rule. + +- Informed: the n heads of dense_T8192_s0 with the largest share of attention inside that window. The + shares were computed per head by `scripts/theory_figures.py` on 2026-10-20 and are stored in + `results/fineweb/theory_figures_data.json`; they run from about 0.5 in layers 0 to 2 to 0.2 to 0.3 in + layers 9 to 11. I ranked by this share because a window keeps only the attention inside it, and the + heads needing the fewest keys (layers 9 to 11, 140 to 190 keys for 90% of the mass) read keys far + outside it. +- Random: one uniform permutation of the 72 slots, cut at n, so the sets are nested as the informed + sets are. + +From random weights only the number of restricted heads per layer matters. Mean window share of the +restricted heads in each set: + +| heads restricted | informed, heads per layer 0 to 11 | share | random, heads per layer 0 to 11 | share | +|---|---|---|---|---| +| 18 | 3 3 2 0 3 1 2 1 1 0 1 1 | 0.69 | 2 1 1 1 1 3 0 4 1 2 0 2 | 0.36 | +| 36 | 4 3 6 3 4 4 2 2 3 1 1 3 | 0.56 | 5 3 2 4 2 3 2 5 1 3 1 5 | 0.39 | +| 54 | 5 6 6 5 5 5 4 5 4 2 3 4 | 0.47 | 6 4 4 6 5 4 3 6 4 3 3 6 | 0.39 | + +Sets: `exp/s2_allocation_sets.py` writes `checkpoints/fineweb/heads/s2_{informed,random}{18,36,54}_T8192.json`. +Queue: `exp/run_s2_allocation.sh` (tmux `s2` on pod laura-sparsity-training, log `/workspace/s2_queue.log`), +order 54, 18, 36, informed before random. Runs are named `s2_{informed,random}_T8192_s0`. One seed. + +### Step 1 results, 2026-10-22, and the change of plan + +Final validation loss against dense_T8192_s0 (3.1845), one seed, 3250 steps at 8192 tokens: + +| heads on the first token plus 31 recent keys | chosen by | final | over dense | at step 1000 | +|---|---|---|---|---| +| 25% (18) | window share | 3.1817 | -0.003 | -0.000 | +| 25% (18) | random | 3.1853 | +0.001 | +0.006 | +| 75% (54) | window share | 3.1852 | +0.001 | -0.003 | +| 75% (54) | random | 3.1834 | -0.001 | -0.002 | +| 100% (72), s1_window32 | all | 3.4237 | +0.239 | +0.301 | + +All four runs train to the dense loss within one run's noise (0.005), whichever heads are restricted, +and the 54-head runs read 0.26 of the dense model's query-key pairs. The 0.24 cost of the 72-head run +therefore comes from restricting the last 18 heads. From random weights the model routes its long-range +work into whichever heads stay dense, so informed and random allocation can only differ when few heads +stay dense, or when the trained model is restricted without retraining. The 36-head runs were dropped +(informed36 stopped at step 250) and the queue was changed to: + +- A, from scratch: 69 and 66 restricted (3 and 6 heads dense), informed (the heads of smallest window + share stay dense: L3H5, L5H0 and L7H1 at 69, which are the induction heads of the trained model) and + random; at 69 also an anti set that keeps dense the 3 heads of largest window share (L2H1, L1H4, + L5H1, previous-token heads). Five runs, about 19 hours. +- B, no training: dense_T8192_s0 with n heads restricted at evaluation time, n in 18, 36, 54, 66, 69 + and 72, informed and random, plus anti at 69, on 64 validation windows (`exp/s2_posthoc.py`, + `results/sparsity/s2_posthoc_T8192.json`). This is the regime in which the ranking was computed. +- C, step 2 shifted to 23 and 22 of 24 groups restricted (3 and 6 heads dense, forced into 1 or 2 + layers), informed and random, plus the dense grouped model. Five runs, about 19 hours. + +### B results, no training, 2026-10-22 + +`results/sparsity/s2_posthoc_T8192.json`: dense_T8192_s0 (3.1845 on these 64 windows) with n heads on +the first token plus 31 recent keys at evaluation time. Loss over dense, and over dense on positions +4096 to 8191: + +| heads restricted | informed | random | anti | +|---|---|---|---| +| 25% (18) | +0.065 (+0.075) | +0.161 (+0.179) | | +| 50% (36) | +0.195 (+0.227) | +0.416 (+0.467) | | +| 75% (54) | +0.448 (+0.502) | +0.516 (+0.551) | | +| 92% (66) | +0.509 (+0.538) | +0.540 (+0.557) | | +| 96% (69) | +0.526 (+0.548) | +0.558 (+0.572) | +0.590 (+0.601) | +| 100% (72) | +0.591 (+0.600) | | | + +Without retraining the window-share ranking costs 2.5 times less than a random choice at 25% and 2.1 +times less at 50%, the anti set at 96% costs the same as restricting every head, and all of the 72-head +cost (0.59) is 2.5 times the cost of the same restriction trained from random weights (0.24). Figure +`figures/sparsity/sparsity_03_informed_vs_random.png` (`scripts/sparsity_figures.py 03`), which gains +the from-scratch points at 66 and 69 as they finish. + +### A and C results, 2026-10-23 + +Trained from random weights, 3250 steps at 8192 tokens, one seed, final loss over the dense model of +the same shape. The gap of every run is constant from step 500 on. + +| dense heads | windowed heads | chosen by | over dense (3.1845) | +|---|---|---|---| +| 18 | 54 | window share / random | +0.001 / -0.001 | +| 6 | 66 | window share / random | +0.019 / +0.018 | +| 3 | 69 | window share (L3H5, L5H0, L7H1) / random (L5H4, L6H0, L9H2) / anti (L1H4, L2H1, L5H1) | +0.035 / +0.036 / +0.038 | +| 0 | 72 | | +0.239 | + +Grouped keys and values, 2 groups of 3 heads per layer, over dense_kv2_T8192_s0 (3.1973, itself ++0.013 over the 6-head dense model): + +| dense groups | windowed groups | chosen by | over dense_kv2 | +|---|---|---|---| +| 1 (3 heads, one layer) | 23 | window share (layer 9) / random (layer 7) | +0.057 / +0.059 | +| 2 (6 heads, two layers) | 22 | window share / random | running | + +- From random weights the cost depends only on how many heads stay dense, within one run's noise: + 18 cost nothing, 6 cost 0.018, 3 cost 0.036, 0 cost 0.24. Which heads stay dense, by window + share, at random, or the most windowed ones, changes the loss by at most 0.003 at every size. + The model routes its long-range work into whatever heads it is given, including three + previous-token slots in layers 1, 2 and 5. +- Three dense heads anywhere recover 85 percent of the all-windowed cost; the cost from 3 dense + heads to none is 0.20, six times the cost from 18 to 3. +- Forcing the 3 dense heads into one layer (one key-value group) costs 0.057 against 0.036 when + they sit in three layers, so the group constraint costs about 0.02 at that size; which layer + again does not matter. +- Without retraining (B above) the choice matters by a factor of 2 to 2.5, so the ranking describes + the trained model and says nothing about which heads a model trained with the restriction needs. + +### Step 2. Whole key-value groups at 8192 tokens + +Track 3's GPT-2 has 6 heads of dimension 128 per layer, so I give it 2 key-value groups per layer, 3 +query heads per group, the ratio of Llama-3.2-3B (`--kv-groups 2` in `exp/f1_fineweb_train.py`). I train +the dense model of that shape (`dense_kv2_T8192_s0`), then restrict 23 or 22 of the 24 groups (all +3 heads of a group; 6, 12 and 18 were planned before step 1's result) to the first token plus 31 recent keys, informed against random. A restricted group +needs 32 cached keys per layer, so the share of groups restricted is the share of the key-value cache +reduced to 32 keys. Step 2 against step 1 at the same share of heads measures what forcing 3 query +heads onto one key set costs. + +- Informed: each layer's 6 heads of dense_T8192_s0 are split by window share into a top 3 and a bottom + 3, each half scores its mean share, and the n halves of largest score are restricted. +- Random: one uniform permutation of the 24 groups, cut at n. + +| groups restricted | informed, groups per layer 0 to 11 | random, groups per layer 0 to 11 | +|---|---|---| +| 22 | 2 2 2 2 2 2 2 2 2 1 1 2 | 1 2 2 2 2 2 2 1 2 2 2 2 | +| 23 | 2 2 2 2 2 2 2 2 2 1 2 2 | 2 2 2 2 2 2 2 1 2 2 2 2 | + +Queue: `exp/run_s2_groups.sh`, which waits for the step 1 queue's end line (log `/workspace/s2g_queue.log`). + +Code, tested on the CPU 2026-10-22: with default groups the attention output equals the file before +the edit bit for bit, dense and with 2 rule heads; with 2 groups the dense output and the output with +group 1 on the rule equal a hand-written grouped attention to 3e-7; a partly restricted group is +refused; `exp/s1_selftest.py` gives 0 failures under Python 3.12 and torch 2.6 (under the laptop's +Python 3.14 and torch 2.11, FlexAttention has no CPU backward and the self-test stops). + +## Code written on 2026-10-19 and what it was tested on + +All of it is on the laptop and copied to the training pod (`/workspace/programmatic-attention`). +`python exp/s1_selftest.py` runs 24 tests on the CPU in about a minute and passes. + +| file | what it does | tested | +|---|---|---| +| `src/sparse_rules.py` | the rule grammar (sink, ind, occ, recent, random, oracle), the per-query budget tensors, the FlexAttention mask function, the dense support, the oracle's bitmask block mask from a dense model's largest keys | every rule equals a pure-Python reference on 288 rows; at most k keys per row; the flex output equals SDPA on the same support to 2e-7 for rules and for the oracle | +| `exp/f1_fineweb_train.py` | `--index-rule`, `--keep-dense`, `--oracle`; index heads run through FlexAttention when a block mask is given; `TeacherTopK` builds the oracle's masks per layer in query chunks | a rule at full budget reproduces the dense loss to 0 in fp32; gradients reach q, k, v, o; keep-dense works; the oracle at full budget equals dense; program, old index and dense modes give losses identical to the file before the edit | +| `exp/s0_pretrained_topk.py` | E0: a Hugging Face model with every head restricted to a rule's keys, loss and coverage per head, per-head restriction | on a random 2-layer Llama: full budget equals dense, coverage 1.000; on Llama-3.2-3B on the laptop GPU, 5 wiki texts: window 128 keeps 0.875 of the attention and costs 0.18 nats, the oracle at 128 keys costs 0.0004 (table below) | +| `exp/f1_sparse_heads.py` | head sets: all heads, all minus a set, the top-n by long-range share or by sink-plus-window coverage from a checkpoint | all three modes on a tiny model | +| `exp/f1_eval_bins.py` | loss of a finished run by position bin and copy class at any T, with a reference run | rule and oracle runs on a tiny model; the dense run equals a direct forward | +| `exp/run_s1_sparsity.sh` | the queue, stages A to E of the plan | syntax only | +| `exp/run_s1_smoke.sh` | 20-step GPU runs of every rule at 8192 tokens with step time and peak memory | not yet run (needs the pod's GPU, busy with fisherworst18 at the time of writing) | + +Not tested, because they need a GPU: the compiled model with a BlockMask input, the flex kernel at +8192 tokens, the step time and peak memory of each rule, the oracle's time at mbs 4, and the +pretrained Llama-3.2-3B at 3B scale. `exp/run_s1_smoke.sh` measures all of them in about 30 minutes. + +## E0 results, Llama-3.2-3B, 300 texts, no training, 2026-10-19 + +`results/sparsity/s0_llama3b_T1024.json`, run on the laptop GPU in 1.9 hours. Every head of the 672 reads at +most k keys per query; the rise is loss minus the dense loss on the same texts, in nats per token; coverage is +the share of the dense attention on the kept keys, averaged over heads and rows 16 and later. Dense losses are +wiki 2.107, math 1.645, code 1.137. + +| rule, every head | set | k 8 | k 32 | k 128 | k 512 | +|---|---|---|---|---|---| +| first token plus recent keys (window) | wiki | +1.183 (0.58) | +0.441 (0.73) | +0.136 (0.88) | +0.022 (0.98) | +| first token plus recent keys (window) | math | +1.373 (0.55) | +0.572 (0.70) | +0.185 (0.86) | +0.020 (0.98) | +| first token plus recent keys (window) | code | +2.137 (0.52) | +0.832 (0.70) | +0.268 (0.86) | +0.032 (0.97) | +| first token, induction matches, then recent (program) | wiki | +1.834 (0.45) | +0.477 (0.69) | +0.097 (0.87) | +0.015 (0.97) | +| first token, induction matches, then recent (program) | math | +1.800 (0.43) | +0.464 (0.67) | +0.125 (0.85) | +0.014 (0.98) | +| first token, induction matches, then recent (program) | code | +2.018 (0.42) | +0.547 (0.67) | +0.146 (0.85) | +0.023 (0.97) | +| first token, previous occurrences, then recent | wiki | +2.734 (0.49) | +0.734 (0.70) | +0.140 (0.87) | +0.022 (0.97) | +| first token, previous occurrences, then recent | math | +3.247 (0.46) | +0.820 (0.67) | +0.184 (0.85) | +0.020 (0.98) | +| first token, previous occurrences, then recent | code | +4.398 (0.44) | +1.369 (0.67) | +0.287 (0.85) | +0.033 (0.97) | +| first token plus the head's own largest keys (oracle) | wiki | +0.118 (0.69) | +0.027 (0.87) | +0.004 (0.97) | +-0.000 (1.00) | +| first token plus the head's own largest keys (oracle) | math | +0.134 (0.67) | +0.028 (0.86) | +0.003 (0.96) | +-0.000 (1.00) | +| first token plus the head's own largest keys (oracle) | code | +0.102 (0.69) | +0.019 (0.87) | +0.001 (0.97) | +-0.000 (1.00) | +| first token plus random keys | wiki | +4.043 (0.19) | +3.171 (0.32) | +2.091 (0.56) | +0.555 (0.86) | +| first token plus random keys | math | +4.582 (0.18) | +3.581 (0.31) | +2.348 (0.54) | +0.589 (0.86) | +| first token plus random keys | code | +5.978 (0.19) | +4.609 (0.31) | +2.891 (0.55) | +0.647 (0.86) | + +Readings. +- The head's own 32 largest keys cost 0.02 to 0.03 nats on all three sets, and 128 keys cost at most 0.004, so a + budget of 32 of 1024 keys is enough when the keys are the right ones. Any indexer's target at k 32 is 0.03. +- The program rule (induction matches before recent keys) costs less than the window on all three sets at k 128 + (0.097, 0.125, 0.146 against 0.136, 0.185, 0.268) and at k 32 on math and code, and more at k 8 on every set, + where its matches displace recent keys the head needs. Previous-occurrence keys cost more than the window at + every k. Random keys cost 2 to 6 nats. +- Coverage does not predict cost. The program rule has lower coverage than the window at every k and lower loss + at k 128; the oracle and the window have the same coverage within 0.14 at k 32 and costs 16 times apart. +- The gap between the program and the oracle at k 32 (0.46 to 0.55 against 0.02 to 0.03) is what training with + the program's support (E1) has to close for H1 to hold; these numbers are for a model never trained on the + restricted support. + +## E1 first results, 2026-10-20 + +Stage A32 started on the old pod at 02:05 UTC on 2026-10-20, 16 hours before intended, because the +other session's screen log gained a note line containing the words "all done" and the queue's guard +matched it; the guard is now anchored to the queue's own end line. The two queues shared the GPU, so +the window run took 8.6 hours; the losses are unaffected. The pod was stopped at about 18:10 UTC +with the program run at step 1250 (resumable from its last.pt). Laura then set the new pod to figures +only, so stage A32 is paused: `window32` done, `program32` at 1250 of 3250, `random32` not started. + +Validation loss at 8192 tokens, every head restricted to 32 keys, one seed, against dense_T8192_s0: + +| step | dense | window (first token plus 31 recent) | program (first token, induction matches, then recent) | +|---|---|---|---| +| 250 | 4.087 | 4.343 (+0.256) | 4.371 (+0.284) | +| 1000 | 3.582 | 3.882 (+0.301) | 3.987 (+0.406) | +| 1250 | 3.518 | 3.816 (+0.298) | 3.934 (+0.416) | +| 3250 | 3.185 | 3.424 (+0.239) | not reached | + +Readings, one seed. +- Training with 32 keys per query on every head ends 0.239 nats above dense at 8192 tokens, and the gap + narrows from 0.30 at step 1000 to 0.24 at 3250. E0's oracle says 32 well-chosen keys cost 0.03 on a + pretrained model, so most of this gap is the choice of keys, not the budget. +- The program rule sits 0.11 to 0.12 nats above the window at every step from 375 on, so at k 32 + putting induction matches ahead of recent keys hurts a model trained that way, as it hurt the + pretrained Llama on wiki at k 32 and on every set at k 8. H1 is not supported at k 32; the k 128 + point, where E0 found the program rule ahead, is the one to run next. + +## What was taken from Tobias's branch, and why + +- **The rule classes follow his template families.** sink is his FIRST, recent is his WIN (the + query itself and the w - 1 keys before it, as in his offsets 0 to w - 1), ind is his IND with + the order made explicit, occ is his OCC. SELF, PREV and DECAY are not rules, since a rule names a + support and those are weightings inside a window. This keeps E0's rules readable against his + atlas and label tables. +- **Coverage is computed the way his `sink_window_support.py` computes it**, as the share of the + dense softmax on the kept keys averaged over rows 16 and later, so E0's coverage numbers can be + put next to his table (0.79, 0.87, 0.91 at windows 16, 64, 128). +- **His stored maps are not used.** The coverage comes from the dense softmax formed in the same + forward pass that scores the restricted model, so E0 needs neither his 318 GB volume nor his + `attention-maps` environment, and perplexity and coverage are measured on one pass. +- **His input sets are the texts for E0**, read in his `inputs.npz` format (ids with BOS, cut at + 1024), so the perplexities are on the 300 texts his atlas describes. Building them needs his + `attention-maps` package (`corpora` then `inputs`), which downloads 724 MB from three public + datasets and needs `pyarrow`. The pod has no GitHub credentials, so the branch has to be copied + from the laptop. `--corpus wikitext` gives the repo's own windows at any T with no download, if + the copy is not wanted. +- **His quality harness and PL hook are not used.** The harness scores TinyStories and WikiText-2 + at 2048 tokens with a post-softmax hook meant for fixed kernels; E0 needs a pre-softmax key + restriction per head and the dense probabilities of the same scores, which a Transformers + attention function gives in 40 lines. + +## What the pod needs before the runs + +1. A Hugging Face token with access to `meta-llama/Llama-3.2-3B` (`hf auth login` on the pod, or + `HF_TOKEN` in the environment). The pod has none and no Llama weights are cached there. +2. `pip install --break-system-packages pyarrow` for Tobias's wiki parquet, and his + `attention-maps` directory copied to the pod (`git worktree add ../pa_tobias origin/tobias_dev` + on the laptop, then scp of `attention-maps/`). +3. `checkpoints/fineweb/dense_T8192_s0/final.pt` (on the pod) for the oracle and the E2 head sets. + +## GPU hours, from the smoke of 2026-10-19 + +`exp/run_s1_smoke.sh` ran 20-step runs on the pod's A100 80 GB at 8192 tokens, mbs 8, compiled. +The step time is read from each run's log over steps 10 to 20, after the compile. Peak memory is +from nvidia-smi. The oracle and the 1024-token row shared the GPU with another queue, so their times +are upper bounds. + +| condition, every head restricted | step s | ratio to dense | peak GB | hours per 3250-step run | +|---|---|---|---|---| +| dense | 4.33 | 1.00 | 35.6 | 4.0 (measured) | +| window, k 32 | 3.54 | 0.82 | 36.7 | 3.2 | +| random, k 32 | 8.20 | 1.89 | 36.7 | 7.4 | +| program (sink, induction, recent), k 32 | 9.59 | 2.21 | 36.7 | 8.7 | +| program, k 128 | 9.66 | 2.23 | 37.1 | 8.7 | +| sink, induction, occurrence, recent, k 32 | 10.61 | 2.45 | 36.7 | 9.6 | +| program, k 32, 18 heads of layers 5 to 10 kept dense | 8.42 | 1.94 | 36.7 | 7.6 | +| oracle (dense model's largest keys), k 32, mbs 4 | 68 (shared GPU) | 16 | 56.8 | over 40 | +| program, k 32, at 1024 tokens, mbs 64 (dense there is 3.0 s) | 9.5 (shared GPU) | 3.2 | 71.0 | 8.6 | + +The oracle at 8192 tokens forms every layer's (T, T) scores in chunks to find the largest keys, 0.5 s +per layer per microbatch in `exp/s1_mask_timing.py`, so it is out at 8192 tokens and runs at 1024 +tokens through the existing SDPA path. The program rule at 1024 tokens with mbs 64 takes 71 GB, +so a 1024-token rule run needs mbs 16 or 32. + +Where the program rule's 2.2x goes. `exp/s1_mask_timing.py` on random ids gives, per layer and +microbatch, attention forward plus backward of 0.044 s dense, 0.018 s window (block sparsity 95 +percent), 0.060 s induction (83 percent) and 0.118 s random (49 percent), with the mask built once +per microbatch in 0.002 to 0.009 s. On random ids induction keys are rare; on text they are many +and spread over the context, so the induction rule's block structure approaches the random rule's, +and nearly half the 128-key blocks are partial blocks that the kernel computes in full and then +masks element by element. The window rule is faster than dense because its keys sit in 2 blocks. +A gather path over the k named keys, (B, H, T, k, hd), would run in time proportional to k and is +the path the method takes at inference; it is about a day of code and is not started. + +| stage | runs | hours on one A100 | +|---|---|---| +| E0 (no training) | 21 settings on 300 texts at 1024 tokens | under 1 on an A100; 2 on the laptop GPU, running | +| E1 core, stage A32 (queued) | window, program, random at k 32 | 19 | +| E1 core, stage A at k 128 | 3 more | 19 | +| E1 rest, stage B | 3 at k 8, 2 at 1024 tokens; the oracle only at 1024 tokens | 35 to 45 | +| E2, stage C | 3 and two head sets | 30 | +| E3, stage D | 3 | 32 | +| bins, stage E | 18 evaluations | 1 | +| total | | about 135; stage A32 alone is 19 | + +Every 8192-token run fits in 80 GB at mbs 8 with 37 GB used. + +Laura's decision of 2026-10-19: one seed, stage A32 first (window, program, random at k 32, 24 hours), +queued on the pod behind the layers-0-to-2 screen queue of another session (about 14 hours). + +## Code still to write + +- The per-head coverage against per-head cost (E0 step 4) exists as `--per-head`; a figure script + for it and for the E1 curve is not written. +- Nothing else. Every run of stages A to E has its command in `exp/run_s1_sparsity.sh`. + +## Decisions for Laura + +1. Whether E0 runs on Tobias's branch with his harness and maps, or on a copy in this repo. His maps + and harness are the fastest route, and the result is his next step 1(b). +2. The k values. The list 8, 32, 128 follows the window sizes run at 1024 tokens; 512 at 8192 tokens would + show where the rules converge. +3. Whether the oracle rule is wanted at 8192 tokens, given that it needs the chunked top-k and a dense + forward per step, or only at 1024 tokens where the existing SDPA path runs it. +4. Whether the final loss at 3250 steps is the measurement, or the step at which each run reaches + 3.28, as in the track-3 rule. The 8192-token dense run reaches 3.28 at step 2625. +5. Seeds. One seed per point first; the contrasts under 0.01 nats need 3 seeds, which triples E1. diff --git a/sparsity/code/f1_fineweb_train.py b/sparsity/code/f1_fineweb_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f67243eb652cf6361e4b2cd41bda3f296f37b07d --- /dev/null +++ b/sparsity/code/f1_fineweb_train.py @@ -0,0 +1,1305 @@ +"""F1: GPT-2 small on FineWeb under the modded-nanogpt track-3 protocol, with a set of +attention heads held to programs, zeroed, or left dense. + +The model, data, batch, optimizer and schedule are those of +records/track_3_optimization/train_gpt_simple.py in +https://github.com/KellerJordan/modded-nanogpt (baseline result 36: 3.2787 at 3250 steps, +n = 10). With no heads held this file trains the same model with the same arithmetic. Three +things are added. + + Held heads. --assignments lists {layer, head, program}. A program head has no query and + no key rows: its output is P @ V_h for the program's (T, T) row-stochastic matrix P, built + once from the program library on a text of length T and verified identical on a second + text (position-only programs only, for now). A zero head has no query, key or value rows + and no columns in the output projection, so its contribution is zero. Muon therefore + never sees a zero-gradient row, and the parameter saving is real. + + Teacher heads. --head-mode teacher --teacher holds the listed heads as program + heads (no query and no key rows, the parameter count of the program run with the same + set) and gives each one, on every microbatch of training and validation, the post-softmax + attention of the same head in the frozen dense model loaded from --teacher, run on the + same input ids. The program names in the assignments file are unused in this mode. + + Extra heads. --head-mode extra keeps every learned head of every layer unchanged and adds, + for each assignments row, one head to that row's layer with its own value rows and output + columns (head_dim 128, trained by the same optimizer groups as the other attention weights) + whose attention is the row's program, resolved as in program mode. The row's head index + only names the slot the program was selected for. A layer with no row is track 3's layer. + + Index heads. --head-mode index keeps the query, key, value and output rows of every held + head and restricts its softmax to the keys its program names: the --index-topk largest + entries of the program's row for that query, plus position 0 unless --index-no-sink, within + the causal mask. The program is resolved as in program mode (a fixed matrix, a ported + text-reading program, or with --teacher the frozen dense model's attention, whose top keys + then name the support). The head's weights over the named keys are learned. Two synthetic + programs exist for this mode at any T: window (the w most recent keys) and prev + (the key d positions back). + + Rule heads. --head-mode index --index-rule restricts every head (or the heads of + --assignments, minus those of --keep-dense) to the keys the rule names for each query, at + most --index-topk of them, and the head learns its weights over them. Rules are the + classes of src/sparse_rules.py joined by '+': sink, ind, occ, recent, random, and + oracle (the largest keys of the frozen dense model in --oracle). The support runs through + FlexAttention, so any T works; one block mask per microbatch serves every rule head of + every layer, and the oracle builds one per layer from the dense model's scores. + + Grouped keys and values. --kv-groups G gives every layer G key-value groups shared by its query + heads (heads 0 to H/G - 1 read group 0, and so on), as in grouped-query attention. The key and + value projections have G * 128 rows. Dense and rule-index heads only; a rule restricts whole groups. + + Fine-tuning. --init starts from a saved dense model: the rows of the kept heads + are copied and the removed rows are dropped. Fresh optimizer states. + + Logging and resume. A JSONL log per run, a results JSON with steps to each threshold and + the track's significance rule, a rolling resume checkpoint with both optimizer states, and + the final weights. + + torchrun --standalone --nproc_per_node=1 exp/f1_fineweb_train.py --run-name dense_s0 + torchrun --standalone --nproc_per_node=1 exp/f1_fineweb_train.py --run-name fixed18_s0 \\ + --assignments checkpoints/fineweb/heads/fixed18_s0.json +""" +import argparse +import json +import os +import re +import sys +import time +import uuid +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.optim import AdamW + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from torch.nn.attention.flex_attention import flex_attention # noqa: E402 +from src.sparse_rules import RuleSupport, oracle_block_mask, parse_rule, topk_keys # noqa: E402 +from src.sparse_rules import RARE_ANCHORS, RARE_CUTOFF, RareAnchorsSupport, rare_anchors_tables # noqa: E402 + +THRESHOLDS = (5.0, 4.5, 4.0, 3.75, 3.6, 3.5, 3.45, 3.4, 3.35, 3.3, 3.28) +TARGET = 3.28 + + +def parse_args(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--run-name", required=True) + ap.add_argument("--steps", type=int, default=3250, help="track 3's baseline length") + ap.add_argument("--T", type=int, default=1024, + help="sequence length, 1024 in track 3; tokens per step stay 524288. Above 1024 only " + "fixed programs (window, prev, meanpat) and --teacher are supported") + ap.add_argument("--assignments", default=None, + help="JSON with an 'assignments' list of {layer, head, program}; none = dense") + ap.add_argument("--head-mode", default="program", choices=("program", "zero", "scaffold", "teacher", "extra", "index"), + help="program: output P @ V; zero: the head is removed; scaffold: the head keeps " + "its weights and its attention is pulled toward the program by a KL penalty; " + "teacher: output A @ V with A the same head's attention in the frozen --teacher model; " + "extra: every learned head stays and one program head per row is added to its layer; " + "index: the head keeps q, k, v and o and its softmax runs only over the keys its " + "program names (the --index-topk largest entries of the program row, plus position 0)") + ap.add_argument("--kv-groups", type=int, default=None, + help="key-value groups per layer shared by the query heads (grouped-query attention); " + "none = one per head, track 3's model") + ap.add_argument("--index-topk", type=int, default=8, + help="index: keys per query taken from the program's row (its largest entries)") + ap.add_argument("--index-no-sink", action="store_true", + help="index: do not add position 0 to every query's key set") + ap.add_argument("--index-rule", default=None, + help="index: a src/sparse_rules.py rule naming each query's keys, at most --index-topk of them, " + "for every head (or the heads of --assignments); program names are then unused") + ap.add_argument("--keep-dense", default=None, + help="index with --index-rule: a head-set JSON whose heads stay dense") + ap.add_argument("--oracle", default=None, + help="index with --index-rule oracle: a dense final.pt whose largest keys per query are the support") + ap.add_argument("--rare-cutoff", type=float, default=RARE_CUTOFF, + help="index with --index-rule sink+rare+anchors: a token is rare when its log unigram frequency " + "log((count + 1) / (total + 50304)) in data/fineweb10B/fineweb_train_000001.bin is below " + "this (the late-heads analysis used -9); the counts are cached under --ckpt-root") + ap.add_argument("--teacher", default=None, + help="teacher mode: a dense final.pt of the same architecture whose attention the held heads read") + ap.add_argument("--kl-weight", type=float, default=1.0, help="scaffold: penalty weight per token") + ap.add_argument("--kl-until", type=int, default=150, help="scaffold: full weight until this step") + ap.add_argument("--kl-zero-at", type=int, default=400, help="scaffold: weight reaches 0 at this step") + ap.add_argument("--init", default="random", help="'random' or a final.pt to fine-tune from") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--lr-scale", type=float, default=1.0, help="multiplies every learning rate") + ap.add_argument("--warmup", type=int, default=0, help="linear warmup steps (0 in track 3)") + ap.add_argument("--cooldown-frac", type=float, default=0.7) + ap.add_argument("--data-dir", default="data/fineweb10B") + ap.add_argument("--texts", default="data/fineweb_val_windows.json", + help="decoded validation windows the program matrices are built from") + ap.add_argument("--upstream", default="upstream/explaining_attention_heads/data") + ap.add_argument("--ckpt-root", default="checkpoints/fineweb") + ap.add_argument("--log-root", default="logs/fineweb") + ap.add_argument("--out", default=None, help="results JSON; default results/fineweb/f1_.json") + ap.add_argument("--save-every", type=int, default=250) + ap.add_argument("--log-every", type=int, default=10) + ap.add_argument("--meanpat", default="checkpoints/fineweb/heads/meanpat_dense_s0.npz", + help="npz of mean attention patterns, keys LH, for programs named meanpat:LH") + ap.add_argument("--save-steps", default="", help="comma-separated steps at which to save weights-only snapshots") + ap.add_argument("--val-early", type=int, default=0, help="validate every 25 steps while step < this") + ap.add_argument("--val-dense-from", type=int, default=None, + help="validate every 25 steps from this step on (default: the last 10 percent, as track 3)") + ap.add_argument("--feat-dir", default="data/f1_features", + help="per-window features from exp/f1_features.py, read when a held program is a port") + ap.add_argument("--mbs", type=int, default=64, help="sequences per microbatch (64 in track 3)") + ap.add_argument("--no-compile", action="store_true") + ap.add_argument("--no-resume", action="store_true") + ap.add_argument("--keep-last", action="store_true") + # ---- method flags (2026-10-12); every default reproduces the run without them ---------- + ap.add_argument("--num-layers", type=int, default=12, help="blocks of the trained model (12 in track 3)") + ap.add_argument("--model-dim", type=int, default=768, help="width of the trained model, a multiple of 128") + ap.add_argument("--data-skip", type=int, default=0, + help="training batches passed over before step 0; 4520 gives batches no 4500-step run reads") + ap.add_argument("--stop-at", type=int, default=None, + help="end the run at this step with the learning-rate schedule of --steps (a screen)") + ap.add_argument("--kl-every", type=int, default=1, + help="scaffold: the KL term on microbatches 0, k, 2k, ... of each step only, its weight times k") + ap.add_argument("--kl-detach", action="store_true", + help="scaffold: the KL gradient reaches only the scaffold heads' q and k rows and the layer's input norm") + ap.add_argument("--teacher-shuffle", action="store_true", + help="teacher: each sequence's held heads read the teacher's attention computed on the " + "previous sequence of the microbatch (same position statistics, wrong text)") + ap.add_argument("--teacher-topk", type=int, default=None, + help="teacher: keep the K largest entries of each supplied attention row and renormalise") + ap.add_argument("--teacher-meanpat", action="store_true", + help="teacher: supply each held head's position-only mean pattern from --meanpat (one (T, T) " + "matrix per head, broadcast over the batch) in place of the teacher's attention") + ap.add_argument("--qk-slow-mult", type=float, default=1.0, + help="multiplies the q and k learning rates of --qk-slow-layers early (Zhu et al. 2026 use 0.25)") + ap.add_argument("--qk-slow-layers", default="", help="layers whose q and k are slowed, as '6-11' or '6,7,8'") + ap.add_argument("--qk-slow-until", type=int, default=0, help="the multiplier holds until this step") + ap.add_argument("--qk-slow-end", type=int, default=0, help="and rises linearly to 1 at this step") + return ap.parse_args(argv) + + +def parse_layers(spec): + """'6-11' or '6,7,8' -> sorted list of ints; '' -> [].""" + out = set() + for part in [s for s in spec.split(",") if s]: + lo, _, hi = part.partition("-") + out.update(range(int(lo), int(hi or lo) + 1)) + return sorted(out) + + +def qk_slow_factor(step, mult, until, end): + """mult before `until`, linear to 1 at `end`, 1 afterwards.""" + if step < until: + return mult + if step < end: + return mult + (1.0 - mult) * (step - until) / (end - until) + return 1.0 + + +######################################## +# Dataloader # +######################################## + +def _load_data_shard(file: Path): + header = torch.from_file(str(file), False, 256, dtype=torch.int32) + assert header[0] == 20240520, "magic number mismatch in the data .bin file" + assert header[1] == 1, "unsupported version" + num_tokens = int(header[2]) + with file.open("rb", buffering=0) as f: + tokens = torch.empty(num_tokens, dtype=torch.uint16, pin_memory=True) + f.seek(256 * 4) + nbytes = f.readinto(tokens.numpy()) + assert nbytes == 2 * num_tokens, "number of tokens read does not match header" + return tokens + + +def distributed_data_generator(filename_pattern: str, batch_size: int, seq_len=1024, skip=0, where=False): + """Track 3's generator. skip: batches to pass over without transfer (resume). where: also + yield (shard name, index of the batch's first window in that shard).""" + files = sorted(Path(filename_pattern).parent.glob(Path(filename_pattern).name)) + assert files, f"no data files match {filename_pattern}" + assert batch_size % dist.get_world_size() == 0 + local_batch_size = batch_size // dist.get_world_size() + file_iter = iter(files) + cur = next(file_iter) + tokens, pos = _load_data_shard(cur), 0 + while True: + if pos + batch_size + 1 >= len(tokens): + cur = next(file_iter) + tokens, pos = _load_data_shard(cur), 0 + if skip > 0: + skip -= 1 + pos += batch_size + continue + buf = tokens[pos + dist.get_rank() * local_batch_size:][:local_batch_size + 1] + inputs = buf[:-1].to(device="cuda", dtype=torch.int32, non_blocking=True) + targets = buf[1:].to(device="cuda", dtype=torch.int64, non_blocking=True) + shard, w0 = cur.name.replace(".bin", ""), (pos + dist.get_rank() * local_batch_size) // seq_len + pos += batch_size + if where: + yield inputs.view(-1, seq_len), targets.view(-1, seq_len), shard, w0 + else: + yield inputs.view(-1, seq_len), targets.view(-1, seq_len) + + +######################################## +# Architecture # +######################################## + +class RMSNorm(nn.Module): + def __init__(self, dim): + super().__init__() + self.gains = nn.Parameter(torch.ones(dim)) + + def forward(self, x): + return F.rms_norm(x, (x.size(-1),), weight=self.gains.type_as(x)) + + +class Linear(nn.Linear): + def __init__(self, in_features, out_features): + super().__init__(in_features, out_features, bias=True) + + def forward(self, x): + return F.linear(x, self.weight.type_as(x), self.bias.type_as(x)) + + +class Rotary(nn.Module): + def __init__(self, dim: int): + super().__init__() + angular_freq = (1 / 1024) ** torch.linspace(0, 1, steps=dim // 4, dtype=torch.float32) + self.register_buffer("angular_freq", torch.cat([angular_freq, angular_freq.new_zeros(dim // 4)])) + + def forward(self, x_BTHD: Tensor): + pos = torch.arange(x_BTHD.size(1), dtype=torch.float32, device=x_BTHD.device) + theta = torch.outer(pos, self.angular_freq)[None, :, None, :] + cos, sin = theta.cos(), theta.sin() + x1, x2 = x_BTHD.to(dtype=torch.float32).chunk(2, dim=-1) + y1 = x1 * cos + x2 * sin + y2 = x1 * (-sin) + x2 * cos + return torch.cat((y1, y2), 3).type_as(x_BTHD) + + +def fast_program_spec(name): + """("sink", 0), ("prev", d) or ("window", w) for the programs fast_program_outputs runs + without a (T, T) matrix; None for every other program name.""" + if name == "sink": + return ("sink", 0) + for kind in ("window", "prev"): + if name.startswith(kind) and name[len(kind):].isdigit(): + return (kind, int(name[len(kind):])) + return None + + +def fast_program_outputs(vp: Tensor, specs): + """P @ V for sink, prev and window programs in O(T) per position, equal to the + matrices build_program_matrices gives those names. vp is (B, T, P, hd); specs[p] is the + program of vp[:, :, p]. sink: every row reads position 0. prev: row i reads position + i - d, row 0 reads position 0, rows 1 to d - 1 read nothing. window: row i averages + positions max(0, i - w + 1) to i, computed as a difference of cumulative sums in fp32.""" + B, T, _, hd = vp.shape + outs = [] + for p, (kind, n) in enumerate(specs): + v = vp[:, :, p] # (B, T, hd) + if kind == "sink": + o = v[:, :1].expand(B, T, hd) + elif kind == "prev": + o = F.pad(v, (0, 0, n, 0))[:, :T] if n > 0 else v # row i <- v[i - n] + if n > 0: + o = torch.cat([v[:, :1], o[:, 1:]], dim=1) # row 0 reads position 0 + else: + c = v.float().cumsum(dim=1) + shifted = F.pad(c, (0, 0, n, 0))[:, :T] # c[i - n], zero for i < n + cnt = torch.arange(1, T + 1, device=v.device, dtype=c.dtype).clamp(max=n).view(1, T, 1) + o = ((c - shifted) / cnt).to(v.dtype) + outs.append(o) + return torch.stack(outs, dim=2) + + +class CausalSelfAttention(nn.Module): + """Track 3's attention with some heads held. + + held: {head: "zero" | program_name}. Dense heads go through scaled_dot_product_attention + as in track 3. Program heads keep their value rows and output columns and read the + (T, T) matrix in self.P (set by set_programs). Zero heads have no parameters at all. + A held index at or past num_heads is an extra program head added beside the learned ones. + """ + + def __init__(self, dim: int, head_dim=128, held=None, index=False, index_topk=8, index_sink=True, kv_groups=None): + super().__init__() + self.num_heads = dim // head_dim + self.head_dim = head_dim + self.index, self.index_topk, self.index_sink = bool(index), int(index_topk), bool(index_sink) + self.held = {int(h): m for h, m in (held or {}).items()} + n_slots = max([self.num_heads] + [h + 1 for h in self.held]) + self.dense = [h for h in range(self.num_heads) if h not in self.held] + self.prog = [h for h in range(n_slots) if h in self.held and self.held[h] != "zero"] + self.extra = [h for h in self.prog if h >= self.num_heads] + self.vheads = sorted(self.dense + self.prog) # heads with value rows and output columns + # a layer with every head zeroed keeps only the output bias; no empty Linear layers + # index heads have query and key rows too, laid out with the value rows (self.vheads order) + self.qk_heads = self.vheads if self.index else self.dense + # grouped keys and values: n_kv groups, each read by kv_rep consecutive query heads + self.n_kv = kv_groups or self.num_heads + self.kv_rep = self.num_heads // self.n_kv + if self.n_kv != self.num_heads: + assert self.num_heads % self.n_kv == 0, f"{self.num_heads} heads do not split into {self.n_kv} groups" + assert self.vheads == list(range(self.num_heads)) and (self.index or not self.held), \ + "grouped keys and values need every head present, dense or rule-index" + for g in range(self.n_kv): + members = {h in self.held for h in range(g * self.kv_rep, (g + 1) * self.kv_rep)} + assert len(members) == 1, f"group {g} is partly restricted: a rule restricts whole groups" + n_k = self.n_kv if self.n_kv != self.num_heads else len(self.qk_heads) + n_v = self.n_kv if self.n_kv != self.num_heads else len(self.vheads) + self.q = Linear(dim, len(self.qk_heads) * head_dim) if self.qk_heads else None + self.k = Linear(dim, n_k * head_dim) if self.qk_heads else None + self.v = Linear(dim, n_v * head_dim) if self.vheads else None + self.proj = Linear(len(self.vheads) * head_dim, dim) if self.vheads else None + self.bias = nn.Parameter(torch.zeros(dim)) if not self.vheads else None + self.rotary = Rotary(head_dim) + # value rows and output columns are laid out in self.vheads order; the dense and + # program outputs are computed as [dense..., prog...] and put back in that order + order = self.dense + self.prog + self.register_buffer("dense_v", torch.tensor([self.vheads.index(h) for h in self.dense], + dtype=torch.long), persistent=False) + self.register_buffer("prog_v", torch.tensor([self.vheads.index(h) for h in self.prog], + dtype=torch.long), persistent=False) + self.register_buffer("perm", torch.tensor([order.index(h) for h in self.vheads], + dtype=torch.long), persistent=False) + self.register_buffer("P", torch.zeros(len(self.prog), 1, 1), persistent=False) + self.register_buffer("M", torch.zeros(len(self.prog), 1, 1, dtype=torch.bool), persistent=False) + self.fast = None # [(kind, n)] per program head when set_programs finds only fast programs + + def set_programs(self, mats): + """mats: {program_name: (T, T) tensor}; one row per program head, in self.prog order. + When every program head of the layer runs a sink, prev or window program and the + layer is not in index mode, self.fast holds their specs and forward computes P @ V + with fast_program_outputs (a cumulative sum or a shift) in place of the (T, T) matmul; + the matrices are still built and kept in self.P so both paths can be compared.""" + if self.prog: + self.P = torch.stack([mats[self.held[h]] for h in self.prog]).to(self.P.device) + if self.index: + self.M = self.support(self.P) + specs = [fast_program_spec(self.held[h]) for h in self.prog] + self.fast = specs if (not self.index and all(s is not None for s in specs)) else None + + def support(self, P): + """(..., T, T) bool: the index_topk largest entries of each row of P (ties by position), + plus position 0 when index_sink, within the causal mask.""" + T = P.size(-1) + causal = torch.tril(torch.ones(T, T, dtype=torch.bool, device=P.device)) + k = min(self.index_topk, T) + idx = P.float().masked_fill(~causal, -1.0).topk(k, dim=-1).indices + keep = torch.zeros(P.shape, dtype=torch.bool, device=P.device).scatter_(-1, idx, True) + keep = keep & (P > 0) & causal + if self.index_sink: + keep[..., 0] = True + keep = keep | torch.eye(T, dtype=torch.bool, device=P.device).expand_as(keep) & ~keep.any(-1, keepdim=True) + return keep + + def groups_to_heads(self, t: Tensor): + """(B, T, n_kv, hd) to (B, T, num_heads, hd): each group repeated for its query heads.""" + return t if self.kv_rep == 1 else t.repeat_interleave(self.kv_rep, dim=2) + + def forward(self, x: Tensor, pats=None, mask=None): + """pats: (B, n_prog, T, T) patterns of this layer's program heads for this batch, in + self.prog order; None uses the fixed matrices in self.P. mask: a FlexAttention + BlockMask naming the keys of this layer's index heads (rule mode), which then runs + them through flex_attention over the same q, k and v.""" + B, T = x.size(0), x.size(1) + hd = self.head_dim + if not self.vheads: + return self.bias.type_as(x).expand(B, T, -1) + if not self.prog: + # track 3's path, over the heads that remain + q = self.q(x).view(B, T, len(self.dense), hd) + k = self.k(x).view(B, T, -1, hd) + v = self.groups_to_heads(self.v(x).view(B, T, -1, hd)) + q, k = F.rms_norm(q, (q.size(-1),)), F.rms_norm(k, (k.size(-1),)) + q, k = self.rotary(q), self.groups_to_heads(self.rotary(k)) + y = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), + v.transpose(1, 2), scale=0.12, is_causal=True).transpose(1, 2) + y = y.contiguous().view(B, T, len(self.dense) * hd) + return self.proj(y) + v = self.groups_to_heads(self.v(x).view(B, T, -1, hd)) + parts = [] + if self.index: + q = self.q(x).view(B, T, len(self.vheads), hd) + k = self.k(x).view(B, T, -1, hd) + q, k = F.rms_norm(q, (q.size(-1),)), F.rms_norm(k, (k.size(-1),)) + q, k = self.rotary(q), self.groups_to_heads(self.rotary(k)) + if self.dense: + parts.append(F.scaled_dot_product_attention(q[:, :, self.dense_v].transpose(1, 2), + k[:, :, self.dense_v].transpose(1, 2), + v[:, :, self.dense_v].transpose(1, 2), + scale=0.12, is_causal=True).transpose(1, 2)) + if mask is not None: + parts.append(flex_attention(q[:, :, self.prog_v].transpose(1, 2), + k[:, :, self.prog_v].transpose(1, 2), + v[:, :, self.prog_v].transpose(1, 2), + block_mask=mask, scale=0.12).transpose(1, 2)) + else: + if pats is None: + assert self.M.size(-1) == T, f"program supports built for T={self.M.size(-1)}, got {T}" + bmask = self.M.unsqueeze(0) # (1, P, T, T) + else: + bmask = self.support(pats) # (B, P, T, T) + parts.append(F.scaled_dot_product_attention(q[:, :, self.prog_v].transpose(1, 2), + k[:, :, self.prog_v].transpose(1, 2), + v[:, :, self.prog_v].transpose(1, 2), + attn_mask=bmask, scale=0.12).transpose(1, 2)) + y = torch.cat(parts, dim=2)[:, :, self.perm] + y = y.contiguous().view(B, T, len(self.vheads) * hd) + return self.proj(y) + if self.dense: + q = self.q(x).view(B, T, len(self.dense), hd) + k = self.k(x).view(B, T, len(self.dense), hd) + q, k = F.rms_norm(q, (q.size(-1),)), F.rms_norm(k, (k.size(-1),)) + q, k = self.rotary(q), self.rotary(k) + parts.append(F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), + v[:, :, self.dense_v].transpose(1, 2), + scale=0.12, is_causal=True).transpose(1, 2)) + vp = v[:, :, self.prog_v] # (B, T, P, hd) + if pats is None and self.fast is not None: + parts.append(fast_program_outputs(vp, self.fast)) # P_p @ V_p without P + elif pats is None: + assert self.P.size(-1) == T, f"program matrices built for T={self.P.size(-1)}, got {T}" + parts.append(torch.einsum("ptk,bkpd->btpd", self.P.type_as(vp), vp)) # P_p @ V_p + else: + parts.append(torch.einsum("bptk,bkpd->btpd", pats.type_as(vp), vp)) + y = torch.cat(parts, dim=2)[:, :, self.perm] + y = y.contiguous().view(B, T, len(self.vheads) * hd) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int): + super().__init__() + hdim = 4 * dim + self.fc = Linear(dim, hdim) + self.proj = Linear(hdim, dim) + + def forward(self, x: Tensor): + x = self.fc(x) + x = x.relu().square() + x = self.proj(x) + return x + + +class Block(nn.Module): + def __init__(self, dim: int, held=None, index=False, index_topk=8, index_sink=True, kv_groups=None): + super().__init__() + self.attn = CausalSelfAttention(dim, held=held, index=index, index_topk=index_topk, index_sink=index_sink, + kv_groups=kv_groups) + self.mlp = MLP(dim) + # a layer with every head zeroed adds only the attention bias, so it has no input norm + self.norm1 = RMSNorm(dim) if self.attn.vheads else None + self.norm2 = RMSNorm(dim) + + def forward(self, x: Tensor, pats=None, mask=None): + x = x + self.attn(self.norm1(x) if self.norm1 is not None else x, pats, mask) + x = x + self.mlp(self.norm2(x)) + return x + + +class GPT(nn.Module): + def __init__(self, vocab_size: int, num_layers: int, model_dim: int, held=None, + index=False, index_topk=8, index_sink=True, kv_groups=None): + """held: {layer: {head: "zero" | program}}; index: held heads are index heads; + kv_groups: key-value groups per layer (None, one per head).""" + super().__init__() + held = held or {} + self.embed = nn.Embedding(vocab_size, model_dim).bfloat16() + self.blocks = nn.ModuleList([Block(model_dim, held=held.get(i), index=index, index_topk=index_topk, + index_sink=index_sink, kv_groups=kv_groups) for i in range(num_layers)]) + self.proj = Linear(model_dim, vocab_size) + self.norm1 = RMSNorm(model_dim) + self.norm2 = RMSNorm(model_dim) + + self.scaffold = {} # {layer: [heads]} pulled toward pats by a KL penalty + self.scaffold_on = False # False once the penalty weight has reached zero + self.kl_detach = False # True: the KL reads a detached block input + self.register_buffer("kl_w", torch.zeros(()), persistent=False) + + def scaffold_kl(self, li, h_in, pats): + """Mean over rows and heads of KL(P || A) for this layer's scaffold heads, from the block + input h_in; the same attention arithmetic as the forward pass.""" + attn, heads = self.blocks[li].attn, self.scaffold[li] + B, T = h_in.size(0), h_in.size(1) + hd = attn.head_dim + rows = torch.cat([torch.arange(h * hd, (h + 1) * hd, device=h_in.device) for h in heads]) + q = F.linear(h_in, attn.q.weight[rows].type_as(h_in), attn.q.bias[rows].type_as(h_in)).view(B, T, len(heads), hd) + k = F.linear(h_in, attn.k.weight[rows].type_as(h_in), attn.k.bias[rows].type_as(h_in)).view(B, T, len(heads), hd) + q, k = F.rms_norm(q, (hd,)), F.rms_norm(k, (hd,)) + q, k = attn.rotary(q), attn.rotary(k) + w = torch.matmul(q.transpose(1, 2).float(), k.transpose(1, 2).float().transpose(-2, -1)) * 0.12 + causal = torch.tril(torch.ones(T, T, dtype=torch.bool, device=w.device)) + logA = torch.log_softmax(w.masked_fill(~causal, float("-inf")), dim=-1) # (B, n, T, T) + P = pats.float() + kl = torch.where(P > 0, P * (torch.log(P.clamp_min(1e-12)) - logA), torch.zeros_like(logA)).sum(-1) + return kl.mean() + + def forward(self, inputs: Tensor, targets: Tensor, pats=None, masks=None): + """pats: {layer: (B, n_prog, T, T)} for the layers whose programs vary per batch (program + heads), or the scaffold targets of the layers in self.scaffold. masks: one BlockMask + for every index layer (a rule read from the ids), or {layer: BlockMask} (the oracle).""" + x = self.norm1(self.embed(inputs)) + kl = torch.zeros((), device=x.device) + for li, block in enumerate(self.blocks): + mask = masks.get(li) if isinstance(masks, dict) else masks + if self.scaffold_on and pats is not None and li in self.scaffold: + kl = kl + self.scaffold_kl(li, block.norm1(x.detach() if self.kl_detach else x), pats[li]) + x = block(x, None, mask) + else: + x = block(x, None if pats is None else pats.get(li), mask) + logits = self.proj(self.norm2(x)).float() + logits = 15 * logits * (logits.square() + 15 ** 2).rsqrt() + loss = F.cross_entropy(logits.view(targets.numel(), -1), targets.view(-1), reduction="sum") + if self.scaffold_on and pats is not None: + loss = loss + self.kl_w * kl / max(len(self.scaffold), 1) * targets.numel() + return loss + + +def init_params(model): + """Track 3's initialization, verbatim.""" + for name, p in model.named_parameters(): + w = p.data + if name.endswith("weight"): + if "proj" in name: + w.zero_() + elif "embed" in name: + w.normal_() + else: + w.normal_(std=0.33 ** 0.5 / w.size(-1) ** 0.5) + elif name.endswith("bias"): + w.zero_() + elif name.endswith("gains"): + w.normal_(mean=1, std=0) + else: + raise Exception(f"Uninitialized parameter: {name}") + + +@torch.no_grad() +def init_from_dense(model, sd): + """Copy a dense model's weights into one with held heads: kept rows of q, k, v and kept + columns of attn.proj are sliced by head; everything else copies whole. Returns the + number of parameters dropped.""" + own = model.state_dict() + dropped = 0 + for name, p in own.items(): + if name.endswith("attn.bias") and name not in sd: # a layer with every head zeroed + src = sd[name.replace("attn.bias", "attn.proj.bias")] + p.copy_(src) + li = int(name.split(".")[1]) + dropped += sum(sd[f"blocks.{li}.attn.{w}"].numel() for w in ("v.weight", "v.bias", "proj.weight")) + continue + src = sd[name] + if src.shape == p.shape: + p.copy_(src) + continue + li = int(name.split(".")[1]) + attn = model.blocks[li].attn + hd = attn.head_dim + rows = lambda heads: torch.cat([torch.arange(h * hd, (h + 1) * hd) for h in heads]) + if attn.extra and name.endswith(("v.weight", "v.bias")): + p[:src.size(0)].copy_(src) # the learned heads' rows; the extra rows keep init_params' values + continue + if attn.extra and name.endswith("attn.proj.weight"): + p[:, :src.size(1)].copy_(src) + continue + if name.endswith(("q.weight", "q.bias", "k.weight", "k.bias")): + p.copy_(src[rows(attn.qk_heads)]) + elif name.endswith(("v.weight", "v.bias")): + p.copy_(src[rows(attn.vheads)]) + elif name.endswith("attn.proj.weight"): + p.copy_(src[:, rows(attn.vheads)]) + else: + raise KeyError(f"unexpected shape change in {name}: {tuple(src.shape)} -> {tuple(p.shape)}") + dropped += src.numel() - p.numel() + for li, blk in enumerate(model.blocks): + if blk.attn.q is None: # no dense head: q and k are gone + dropped += sum(sd[f"blocks.{li}.attn.{w}"].numel() for w in ("q.weight", "q.bias", "k.weight", "k.bias")) + if blk.norm1 is None: + dropped += sd[f"blocks.{li}.norm1.gains"].numel() + model.load_state_dict(own) + return dropped + + +class TeacherPatterns(nn.Module): + """The post-softmax attention of a frozen dense model, for a student whose held heads read + it as their pattern. forward(ids) -> {layer: (B, n_held, T, T) bf16}, heads in ascending + order within a layer (the student's attn.prog order). The teacher's blocks run in order + up to the last held layer; at a held layer the held heads' q and k are taken from the + block input as CausalSelfAttention.forward takes them (rms_norm, then rotary), q k^T is + accumulated in fp32 from the bf16 q and k as scaled_dot_product_attention accumulates it, + and softmax(0.12 q k^T + causal mask) is cast to bf16. + + The teacher's depth and width are read from its state dict, so it can be smaller than the + student. tmap {(student layer, head): (teacher layer, head)} gives each held head the + teacher head it reads; with no tmap every held head reads the same head of the teacher. + + topk K keeps the K largest entries of every row and renormalises them (the softmax over + the K largest scores; K at or above T is the full row). meanpat {LH: (T, T)} replaces + each held head's pattern by that fixed matrix broadcast over the batch, and the teacher's + blocks are then not run.""" + + def __init__(self, path, held, T=1024, tmap=None, topk=None, meanpat=None): + super().__init__() + self.topk = topk + self.meanpat = None + if meanpat is not None: + self.meanpat = {int(li): torch.stack([torch.as_tensor(meanpat[f"L{li}H{h}"]) for h in sorted(int(x) for x in hs)]) + .to(torch.bfloat16) for li, hs in held.items()} # {layer: (n_held, T, T)} + for li, m in self.meanpat.items(): + self.register_buffer(f"meanpat{li}", m, persistent=False) + sd = torch.load(path, map_location="cuda", weights_only=False)["model"] + n_layers = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("blocks.")) + self.gpt = GPT(vocab_size=50304, num_layers=n_layers, model_dim=sd["embed.weight"].size(1)) + self.gpt.load_state_dict(sd) + self.gpt.eval().requires_grad_(False) + self.heads = {int(li): sorted(int(h) for h in hs) for li, hs in held.items()} + if tmap is None: + tmap = {(li, h): (li, h) for li, hs in self.heads.items() for h in hs} + self.tmap = {(int(k[0]), int(k[1])): (int(v[0]), int(v[1])) for k, v in tmap.items()} + self.identity = all(k == v for k, v in self.tmap.items()) + theads = {} + for tl, th in self.tmap.values(): + assert tl < n_layers and th < self.gpt.blocks[tl].attn.num_heads, f"teacher has no head L{tl}H{th}" + theads.setdefault(tl, set()).add(th) + self.theads = {tl: sorted(hs) for tl, hs in theads.items()} # teacher heads computed per layer + self.last = max(self.theads) if self.theads else -1 + hd = self.gpt.blocks[0].attn.head_dim + for li, hs in self.theads.items(): + rows = torch.cat([torch.arange(h * hd, (h + 1) * hd) for h in hs]) + self.register_buffer(f"rows{li}", rows, persistent=False) + self.register_buffer("causal", torch.tril(torch.ones(T, T, dtype=torch.bool)), persistent=False) + + def patterns(self, li, h_in): + attn = self.gpt.blocks[li].attn + B, T = h_in.size(0), h_in.size(1) + hd, n = attn.head_dim, len(self.theads[li]) + rows = getattr(self, f"rows{li}") + q = F.linear(h_in, attn.q.weight[rows].type_as(h_in), attn.q.bias[rows].type_as(h_in)).view(B, T, n, hd) + k = F.linear(h_in, attn.k.weight[rows].type_as(h_in), attn.k.bias[rows].type_as(h_in)).view(B, T, n, hd) + q, k = F.rms_norm(q, (hd,)), F.rms_norm(k, (hd,)) + q, k = attn.rotary(q), attn.rotary(k) + q = q.transpose(1, 2).reshape(B * n, T, hd) + k = k.transpose(1, 2).reshape(B * n, T, hd) + s = torch.bmm(q, k.transpose(1, 2), out_dtype=torch.float32).view(B, n, T, T) * 0.12 + s = s.masked_fill(~self.causal[:T, :T], float("-inf")) + if self.topk is not None: + # softmax over the K largest scores of each row is the row's K largest probabilities renormalised + top, idx = s.topk(min(self.topk, T), dim=-1) + return torch.zeros_like(s).scatter_(-1, idx, torch.softmax(top, dim=-1)).to(torch.bfloat16) + return torch.softmax(s, dim=-1).to(torch.bfloat16) + + @torch.no_grad() + def forward(self, ids: Tensor): + if self.meanpat is not None: + B, T = ids.size(0), ids.size(1) + return {li: getattr(self, f"meanpat{li}")[:, :T, :T].unsqueeze(0).expand(B, -1, -1, -1) + for li in self.meanpat} + g = self.gpt + x = g.norm1(g.embed(ids)) + out = {} + for li in range(self.last + 1): + block = g.blocks[li] + if li in self.theads: + out[li] = self.patterns(li, block.norm1(x)) + if li < self.last: + x = block(x) + if self.identity: + return out + # student layer -> its held heads in ascending order, each from its mapped teacher head + return {sl: torch.stack([out[tl][:, self.theads[tl].index(th)] + for tl, th in (self.tmap[(sl, h)] for h in hs)], dim=1) + for sl, hs in self.heads.items()} + + +class TeacherTopK(nn.Module): + """The k largest keys per query of a frozen dense model's heads, as FlexAttention block + masks for a student whose index heads read them (the oracle rule). forward(ids) -> + {layer: BlockMask} over that layer's held heads in the student's attn.prog order. The + teacher's q and k are taken as TeacherPatterns takes them; the scores are formed in query + chunks (src.sparse_rules.topk_keys), so no (T, T) matrix for all heads is held at once. + With sink, position 0 is added and the k - 1 largest keys among positions 1 and later are + taken, so every row has at most k keys.""" + + def __init__(self, path, held, k, sink): + super().__init__() + sd = torch.load(path, map_location="cuda" if torch.cuda.is_available() else "cpu", weights_only=False)["model"] + n_layers = 1 + max(int(x.split(".")[1]) for x in sd if x.startswith("blocks.")) + self.gpt = GPT(vocab_size=50304, num_layers=n_layers, model_dim=sd["embed.weight"].size(1)) + self.gpt.load_state_dict(sd) + self.gpt.eval().requires_grad_(False) + self.heads = {int(li): sorted(int(h) for h in hs) for li, hs in held.items()} + self.last = max(self.heads) if self.heads else -1 + self.k, self.sink = int(k), bool(sink) + hd = self.gpt.blocks[0].attn.head_dim + for li, hs in self.heads.items(): + assert li < n_layers and max(hs) < self.gpt.blocks[li].attn.num_heads, f"teacher has no layer {li} head {max(hs)}" + rows = torch.cat([torch.arange(h * hd, (h + 1) * hd) for h in hs]) + self.register_buffer(f"rows{li}", rows, persistent=False) + + @torch.no_grad() + def masks(self, li, h_in): + attn = self.gpt.blocks[li].attn + B, T = h_in.size(0), h_in.size(1) + hd, n = attn.head_dim, len(self.heads[li]) + rows = getattr(self, f"rows{li}") + q = F.linear(h_in, attn.q.weight[rows].type_as(h_in), attn.q.bias[rows].type_as(h_in)).view(B, T, n, hd) + k = F.linear(h_in, attn.k.weight[rows].type_as(h_in), attn.k.bias[rows].type_as(h_in)).view(B, T, n, hd) + q, k = F.rms_norm(q, (hd,)), F.rms_norm(k, (hd,)) + q, k = attn.rotary(q), attn.rotary(k) + kk = self.k - 1 if self.sink else self.k + idx = topk_keys(q.transpose(1, 2), k.transpose(1, 2), kk, 0.12, exclude_sink=self.sink) + return oracle_block_mask(idx, T, self.sink) + + @torch.no_grad() + def forward(self, ids: Tensor): + g = self.gpt + x = g.norm1(g.embed(ids)) + out = {} + for li in range(self.last + 1): + block = g.blocks[li] + if li in self.heads: + out[li] = self.masks(li, block.norm1(x)) + if li < self.last: + x = block(x) + return out + + +######################################## +# Programs # +######################################## + +def program_key(name): + """'gpt2:first_token_bias_L0H9' -> ('gpt2', 'first_token_bias_L0H9'); bare names are gpt2.""" + return tuple(name.split(":", 1)) if ":" in name else ("gpt2", name) + + +def random_pattern(T, seed, k=3): + """Each query attends uniformly to k positions drawn from 0..q (all of them while q < k).""" + rng = np.random.default_rng(seed) + m = np.zeros((T, T)) + for q in range(T): + idx = rng.choice(q + 1, size=min(k, q + 1), replace=False) + m[q, idx] = 1.0 / len(idx) + return m + + +def build_program_matrices(names, texts, T, upstream, dtype=torch.float32, meanpat=None): + """{name: (T, T) tensor} for position-only programs. A program is built on texts[0] and + must give the same matrix on texts[1:], or this raises; a program that reads the text + cannot be cached and is not supported here.""" + from transformers import AutoTokenizer + from src import library + tok = AutoTokenizer.from_pretrained("gpt2") + out, loaded = {}, {} + for name in sorted(set(names)): + if name.startswith("meanpat:"): + # a trained model's mean attention pattern, written by exp/f1_head_analysis.py + mp = np.load(meanpat) + out[name] = torch.from_numpy(mp[name.split(":", 1)[1]]).to(dtype) + continue + if name == "sink": + # every query attends to position 0; fast_program_outputs runs it without a matrix + m = torch.zeros(T, T, dtype=dtype) + m[:, 0] = 1.0 + out[name] = m + continue + if name.startswith("window") or name.startswith("prev"): + # window: uniform over the w most recent keys; prev: the key d back (index mode) + n = int(name[len("window"):]) if name.startswith("window") else int(name[len("prev"):]) + i = torch.arange(T)[:, None] + j = torch.arange(T)[None, :] + keep = ((i - j) < n) & (j <= i) if name.startswith("window") else ((i - j) == n) + keep[0, 0] = True + m = keep.to(dtype) + out[name] = m / m.sum(-1, keepdim=True).clamp_min(1) + continue + if name.startswith("random"): + # random_, as in src/automata_programs.random3_ + head, seed = name.split("_", 1) + k = int(head[len("random"):]) if len(head) > len("random") else 3 + out[name] = torch.from_numpy(random_pattern(T, int(seed), k)).to(dtype) + continue + key, prog = program_key(name) + if key not in loaded: + progs, mod = library.load_programs(key, upstream) + if key == "llama3b": + library.install_helpers(mod, tok, None) + loaded[key] = progs + mats = [] + for t in texts: + m = library.program_matrix(loaded[key], prog, t, tok, expect=T) + if m is None: + raise RuntimeError(f"program {name} failed at T={T}") + mats.append(m) + if not all(np.allclose(mats[0], m, atol=1e-9, rtol=0.0) for m in mats[1:]): + raise RuntimeError(f"program {name} is not position-only at T={T}") + out[name] = torch.from_numpy(mats[0]).to(dtype) + return out + + +def load_assignments(path, mode, num_heads=6): + """{layer: {head: 'zero' | program}} and the raw rows. In extra mode the rows of a layer, + in head order, become heads num_heads, num_heads + 1, ... of that layer.""" + rows = json.load(open(path)) + rows = rows["assignments"] if isinstance(rows, dict) else rows + held = {} + if mode == "extra": + for r in sorted(rows, key=lambda r: (int(r["layer"]), int(r["head"]))): + hs = held.setdefault(int(r["layer"]), {}) + hs[num_heads + len(hs)] = r["program"] + return held, rows + for r in rows: + held.setdefault(int(r["layer"]), {})[int(r["head"])] = "zero" if mode == "zero" else r["program"] + return held, rows + + +######################################## +# Optimizer # +######################################## + +def zeropower_via_newtonschulz5(G: Tensor) -> Tensor: + assert G.ndim >= 2 + X = G.bfloat16() + if G.size(-2) > G.size(-1): + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + 1e-7) + a, b, c = 2, -1.5, 0.5 + for _ in range(12): + A = X @ X.mT + B = b * A + c * A @ A + X = a * X + B @ X + if G.size(-2) > G.size(-1): + X = X.mT + return X + + +@torch.compile +def muon_update(grad, momentum, mu=0.95, nesterov=True): + momentum.lerp_(grad, 1 - mu) + update = grad.lerp_(momentum, mu) if nesterov else momentum + update = zeropower_via_newtonschulz5(update) + update *= max(1, grad.size(-2) / grad.size(-1)) ** 0.5 + return update + + +class Muon(torch.optim.Optimizer): + def __init__(self, params, lr=0.02, weight_decay=0.01, mu=0.95): + defaults = dict(lr=lr, weight_decay=weight_decay, mu=mu) + params = list(params) + assert all(isinstance(p, Tensor) for p in params) + super().__init__(params, defaults) + + @torch.no_grad() + def step(self): + world_size = dist.get_world_size() + rank = dist.get_rank() + for group in self.param_groups: + params = group["params"] + params_pad = params + [torch.empty_like(params[-1])] * (world_size - len(params) % world_size) + for base_i in range(0, len(params), world_size): + if base_i + rank < len(params): + p = params[base_i + rank] + state = self.state[p] + if len(state) == 0: + state["momentum"] = torch.zeros_like(p) + update = muon_update(p.grad, state["momentum"], mu=group["mu"]) + p.mul_(1 - group["lr"] * group["weight_decay"]) + p.add_(update, alpha=-group["lr"]) + dist.all_gather(params_pad[base_i:base_i + world_size], params_pad[base_i + rank]) + + +######################################## +# Main # +######################################## + +def main(argv=None): + a = parse_args(argv) + device = torch.device("cuda", int(os.environ["LOCAL_RANK"])) + torch.cuda.set_device(device) + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + assert 8 % dist.get_world_size() == 0 + rank0 = dist.get_rank() == 0 + sys.stdout.reconfigure(line_buffering=True) + + if torch.get_num_threads() > 16: + torch.set_num_threads(8) # the container has 31 cores, not the 252 reported + name = a.run_name + ck_dir = os.path.join(a.ckpt_root, name) + os.makedirs(ck_dir, exist_ok=True) + os.makedirs(a.log_root, exist_ok=True) + log_path = os.path.join(a.log_root, f"{name}.jsonl") + out_path = a.out or os.path.join("results", "fineweb", f"f1_{name}.json") + last_path = os.path.join(ck_dir, "last.pt") + + def say(s): + if rank0: + print(f"[f1] {s}") + + # ---- heads held -------------------------------------------------------------------- + T = a.T + held, rows = ({}, []) if a.assignments is None else load_assignments(a.assignments, a.head_mode, + num_heads=a.model_dim // 128) + rule = None + if a.index_rule is not None: + assert a.head_mode == "index", "--index-rule needs --head-mode index" + # 2026-10-20: sink+rare+anchors is the late-heads candidate set of exp/f1_late_programs.py, + # one rule name without a key budget (src/sparse_rules.py RareAnchorsSupport) + classes = ["sink", "rare", "anchors"] if a.index_rule == RARE_ANCHORS else parse_rule(a.index_rule) + if a.assignments is None: # every head of every layer + held = {li: {h: "rule" for h in range(a.model_dim // 128)} for li in range(a.num_layers)} + rows = [{"layer": li, "head": h, "program": "rule"} for li in held for h in held[li]] + if a.keep_dense: + kd = load_assignments(a.keep_dense, "program")[1] + for r in kd: + held.get(int(r["layer"]), {}).pop(int(r["head"]), None) + held = {li: hs for li, hs in held.items() if hs} + rows = [{"layer": li, "head": h, "program": "rule"} for li in sorted(held) for h in sorted(held[li])] + if "oracle" in classes: + assert a.oracle, "--index-rule oracle needs --oracle " + elif a.index_rule == RARE_ANCHORS: + tables = rare_anchors_tables(os.path.join(a.ckpt_root, "rare_anchors_vocab_fineweb_train_000001.npz"), + os.path.join(a.data_dir, "fineweb_train_000001.bin")) + rule = RareAnchorsSupport(tables, a.rare_cutoff) + else: + rule = RuleSupport(a.index_rule, a.index_topk) + n_held = sum(len(v) for v in held.values()) + scaffold = held if a.head_mode == "scaffold" else {} + if a.head_mode == "scaffold": + held = {} # the model keeps every head; the programs are targets + mats, ported, store = {}, [], None + if a.head_mode in ("program", "scaffold", "extra", "index") and n_held and not (a.head_mode in ("extra", "index") and a.teacher) \ + and a.index_rule is None: + from src import f1_programs as fp + names = sorted(set(part for r in rows for part in r["program"].split("+"))) # "a+b" is the union of a and b + ported = [n for n in names if n in fp.PORTS] + fixed = [n for n in names if n not in fp.PORTS] + assert not ported or T == 1024, "ported text-reading programs read 1024-token feature windows" + if fixed: + texts = [w["text"] for w in json.load(open(a.texts))[:3]] + mats = build_program_matrices(fixed, texts, T, a.upstream, meanpat=a.meanpat) + say(f"{len(mats)} fixed program matrices at T={T} (verified position-only), {len(ported)} ported programs") + if any(n not in fp.ID_ONLY for n in ported): + from transformers import AutoTokenizer + store = fp.FeatureStore(a.feat_dir, AutoTokenizer.from_pretrained("gpt2"), device="cuda") + + # ---- model --------------------------------------------------------------------------- + torch.manual_seed(a.seed) + model = GPT(vocab_size=50304, num_layers=a.num_layers, model_dim=a.model_dim, held=held, + index=a.head_mode == "index", index_topk=a.index_topk, index_sink=not a.index_no_sink, + kv_groups=a.kv_groups).cuda() + init_params(model) + dropped = 0 + if a.init != "random": + sd = torch.load(a.init, map_location="cuda", weights_only=False)["model"] + dropped = init_from_dense(model, sd) + say(f"initialized from {a.init}; dropped {dropped} parameters of held heads") + for blk in model.blocks: + if blk.attn.prog and not ported and a.head_mode != "teacher" and not (a.head_mode in ("extra", "index") and a.teacher) \ + and a.index_rule is None: + blk.attn.set_programs({k: v.cuda() for k, v in mats.items()}) + fixed_gpu = {k: v.cuda() for k, v in mats.items()} + from src import f1_programs as fp + builder = None + if a.head_mode in ("program", "extra", "index") and n_held and not (a.head_mode in ("extra", "index") and a.teacher) \ + and a.index_rule is None: + builder = fp.PatternBuilder(model, fixed_gpu, store) + elif a.head_mode == "scaffold" and n_held: + # a pattern builder over a stand-in with the scaffold heads as program heads + from types import SimpleNamespace + model.scaffold = {li: sorted(hs) for li, hs in scaffold.items()} + spec = SimpleNamespace(blocks=[SimpleNamespace(attn=SimpleNamespace( + prog=model.scaffold.get(li, []), held=scaffold.get(li, {}))) for li in range(a.num_layers)]) + builder = fp.PatternBuilder(spec, fixed_gpu, store) + model.scaffold_on = True + teacher = None + if a.head_mode == "teacher" and n_held: + assert a.teacher, "--head-mode teacher needs --teacher " + if a.head_mode in ("teacher", "scaffold", "extra", "index") and n_held and a.teacher: + # scaffold with --teacher: the KL pull targets the teacher's attention instead of the programs. + # index with --teacher: the teacher's largest entries name each held head's keys. + # extra with --teacher: each extra head reads the teacher's attention for the (layer, head) of its + # row; load_assignments numbers the extra heads in ascending row-head order, which is the order + # TeacherPatterns returns, so the per-layer pats line up with attn.prog. + if a.head_mode == "extra": + t_held = {} + for r in rows: + t_held.setdefault(int(r["layer"]), {})[int(r["head"])] = r["program"] + else: + t_held = scaffold if a.head_mode == "scaffold" else held + # rows with teacher_layer and teacher_head read that head of the teacher (a teacher of another shape) + tmap = None + if any("teacher_layer" in r for r in rows): + tmap = {(int(r["layer"]), int(r["head"])): (int(r["teacher_layer"]), int(r["teacher_head"])) for r in rows} + mp = dict(np.load(a.meanpat)) if a.teacher_meanpat else None + teacher = TeacherPatterns(a.teacher, t_held, T=T, tmap=tmap, topk=a.teacher_topk, meanpat=mp).cuda() + say(f"teacher {a.teacher}: {n_held} heads in {len(teacher.heads)} layers read its attention" + + ("" if teacher.identity else f" through a head map onto its {len(teacher.gpt.blocks)} layers") + + (f", top-{a.teacher_topk} entries of each row renormalised" if a.teacher_topk else "") + + (f", replaced by the mean patterns of {a.meanpat}" if a.teacher_meanpat else "")) + model.kl_detach = a.kl_detach + oracle = None + if a.index_rule is not None and rule is None: + oracle = TeacherTopK(a.oracle, held, a.index_topk, sink="sink" in classes).cuda() + say(f"oracle {a.oracle}: {n_held} heads in {len(oracle.heads)} layers read its {a.index_topk} largest keys per query" + + (" (position 0 plus the largest among the rest)" if oracle.sink else "")) + if a.index_rule == RARE_ANCHORS: + say(f"rule {a.index_rule} on {n_held} heads: the sink, the query, the 8 previous tokens, the document's rare " + f"tokens (log frequency below {a.rare_cutoff}: {rule.n_rare} token types, {100 * rule.rare_share:.1f}% of " + f"the counted tokens), form-induction keys, the last <|endoftext|> and the token after it, and the 8 " + f"most recent boundary tokens; no key budget" + + (f" (the heads of {a.keep_dense} stay dense)" if a.keep_dense else "")) + elif a.index_rule is not None: + say(f"rule {a.index_rule}, at most {a.index_topk} keys per query, on {n_held} heads" + + (f" (the heads of {a.keep_dense} stay dense)" if a.keep_dense else "")) + + def build_masks(ids): + """The BlockMask of the rule for this microbatch (shared by every index layer), or the + oracle's {layer: BlockMask}; None when no rule is set.""" + if rule is not None: + return rule.block_mask(ids) + if oracle is not None: + return oracle(ids) + return None + + def build_pats(shard, w0, ids): + """{layer: (B, n_prog, T, T) bf16} for one microbatch, or None when every program is fixed.""" + if teacher is not None: + if a.head_mode == "scaffold" and not model.scaffold_on: + return None + return teacher(ids.roll(1, dims=0) if a.teacher_shuffle else ids) + if builder is None or (not builder.ported and a.head_mode != "scaffold"): + return None + if a.head_mode == "scaffold": + if not model.scaffold_on: + return None + if not builder.ported: + return builder.fixed_only(ids.size(0)) + if store is not None: + nxt = re.sub(r"(\d+)$", lambda m: f"{int(m.group(1)) + 1:06d}", shard) + store.prefetch(nxt) # the following training shard, read in a thread + return builder(shard, w0, ids) + + n_params = sum(p.numel() for p in model.parameters()) + heads_msg = f"{n_held} extra heads added" if a.head_mode == "extra" else f"{n_held} of 72 heads held ({a.head_mode})" + say(f"{name}: {n_params} parameters, {heads_msg}, " + f"{a.steps} steps of 524288 tokens, seed {a.seed}, init {a.init}") + if not a.no_compile: + model.compile(dynamic=False) + if teacher is not None: + teacher.compile(dynamic=False) + if oracle is not None: + oracle.gpt.compile(dynamic=False) + + # ---- data ---------------------------------------------------------------------------- + batch_size = 8 * 64 * 1024 + val_tokens = 8 * 64 * 1024 + mbs = a.mbs + val_shard = "fineweb_val_000000" + val_inputs, val_targets = next(distributed_data_generator( + os.path.join(a.data_dir, "fineweb_val_*.bin"), val_tokens, seq_len=T)) + + # ---- optimizers (track 3) -------------------------------------------------------------- + # --qk-slow-*: the q and k weights and biases of the slowed layers go to groups of their own, + # marked qk_slow, whose learning rate set_hparams multiplies by qk_slow_factor + slow_layers = parse_layers(a.qk_slow_layers) if a.qk_slow_mult != 1.0 else [] + slow = [getattr(model.blocks[li].attn, n).weight for li in slow_layers for n in ("q", "k") + if model.blocks[li].attn.q is not None] + slow_b = [getattr(model.blocks[li].attn, n).bias for li in slow_layers for n in ("q", "k") + if model.blocks[li].attn.q is not None] + slow_ids = set(id(p) for p in slow + slow_b) + optimizer1 = AdamW([dict(params=[model.embed.weight], lr=0.7 * a.lr_scale), + dict(params=[model.proj.weight], lr=0.004 * a.lr_scale), + dict(params=[p for p in model.parameters() if p.ndim < 2 and id(p) not in slow_ids], + lr=0.015 * a.lr_scale)], + betas=(0.8, 0.95), eps=1e-10, weight_decay=0.001, fused=True) + optimizer2 = Muon([p for p in model.blocks.parameters() if p.ndim >= 2 and id(p) not in slow_ids], + lr=0.025 * a.lr_scale, weight_decay=0.05) + if slow: + optimizer1.add_param_group(dict(params=slow_b, lr=0.015 * a.lr_scale, qk_slow=True)) + optimizer2.add_param_group(dict(params=slow, qk_slow=True)) + say(f"q and k of layers {slow_layers} ({len(slow)} matrices, {len(slow_b)} biases): learning rate times " + f"{a.qk_slow_mult} to step {a.qk_slow_until}, rising to 1 at step {a.qk_slow_end}") + optimizers = [optimizer1, optimizer2] + assert set(p for opt in optimizers for group in opt.param_groups + for p in group["params"]) == set(model.parameters()) + for opt in optimizers: + for group in opt.param_groups: + group["initial_lr"] = group["lr"] + + def set_hparams(step): + progress = step / a.steps + assert 0 <= progress < 1 + if progress < 1 - a.cooldown_frac: + eta = 1.0 + else: + eta = (1 - progress) / a.cooldown_frac + if a.warmup and step < a.warmup: + eta *= (step + 1) / a.warmup + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["initial_lr"] * eta + if group.get("qk_slow"): + group["lr"] *= qk_slow_factor(step, a.qk_slow_mult, a.qk_slow_until, a.qk_slow_end) + + # ---- resume -------------------------------------------------------------------------- + step0, training_time, log_rows = 0, 0.0, [] + if not a.no_resume and os.path.exists(last_path): + st = torch.load(last_path, map_location="cuda", weights_only=False) + model.load_state_dict(st["model"]) + for opt, s in zip(optimizers, st["optimizers"]): + opt.load_state_dict(s) + step0, training_time = st["step"], st["training_time"] + log_rows = [json.loads(l) for l in open(log_path)] if os.path.exists(log_path) else [] + log_rows = [r for r in log_rows if r["step"] <= step0] + say(f"resumed at step {step0} from {last_path}") + if rank0: + with open(log_path, "w") as f: + for r in log_rows: + f.write(json.dumps(r) + "\n") + + def save_last(step): + if not rank0: + return + tmp = last_path + ".tmp" + torch.save({"model": model.state_dict(), "optimizers": [o.state_dict() for o in optimizers], + "step": step, "training_time": training_time + (time.perf_counter() - t0)}, tmp) + os.replace(tmp, last_path) + + meta = {"experiment": "f1_fineweb_train", "run": name, "args": vars(a), "n_params": n_params, + "n_heads_held": n_held, "head_mode": a.head_mode if n_held else "dense", + "assignments": rows, "params_dropped_at_init": dropped, "ported_programs": ported, + "scaffold": {"kl_weight": a.kl_weight, "kl_until": a.kl_until, "kl_zero_at": a.kl_zero_at} if a.head_mode == "scaffold" else None, + "teacher": a.teacher if a.head_mode in ("teacher", "scaffold", "extra", "index") and n_held and a.teacher else None, + "n_heads_extra": n_held if a.head_mode == "extra" else 0, + "index": {"topk": a.index_topk, "sink": not a.index_no_sink} if a.head_mode == "index" else None, + "index_rule": ({"rule": a.index_rule, "topk": a.index_topk, "keep_dense": a.keep_dense, "oracle": a.oracle, + "rare_cutoff": a.rare_cutoff if a.index_rule == RARE_ANCHORS else None} + if a.index_rule is not None else None), + "teacher_topk": a.teacher_topk, "teacher_meanpat": a.meanpat if a.teacher_meanpat else None, + "teacher_shuffle": a.teacher_shuffle, + "fixed_programs": sorted(mats), + "torch": str(torch.__version__), "device": torch.cuda.get_device_name(device), + "protocol": f"modded-nanogpt track 3 baseline (result 36), batch 524288, T {T}"} + + train_loader = distributed_data_generator(os.path.join(a.data_dir, "fineweb_train_*.bin"), + batch_size, seq_len=T, skip=step0 + a.data_skip, where=True) + for p in model.parameters(): + dist.broadcast(p.detach(), 0) + + def log(rec): + log_rows.append(rec) + if rank0: + with open(log_path, "a") as f: + f.write(json.dumps(rec) + "\n") + + def validate(): + model.eval() + val_loss = torch.zeros((), device="cuda") + with torch.no_grad(): + assert len(val_inputs) % mbs == 0 + for i in range(len(val_inputs) // mbs): + vi = val_inputs[i * mbs:(i + 1) * mbs] + val_loss += model(vi, val_targets[i * mbs:(i + 1) * mbs], + None if a.head_mode == "scaffold" else build_pats(val_shard, i * mbs, vi), + build_masks(vi)) + dist.all_reduce(val_loss, op=dist.ReduceOp.SUM) + model.train() + return float(val_loss / val_tokens) + + # ---- training ------------------------------------------------------------------------ + last_val_step = step0 + dist.barrier() + t0 = time.perf_counter() + train_loss, n_loss = 0.0, 0 + end = a.stop_at if a.stop_at is not None else a.steps # the last step; the schedule is that of --steps + assert 0 < end <= a.steps + for step in range(step0, end + 1): + val_step_freq = 125 if step / a.steps < 0.9 else 25 + if step < a.val_early or (a.val_dense_from is not None and step >= a.val_dense_from): + val_step_freq = 25 + if (step == end or step % val_step_freq == 0) and not (step == step0 and step0 > 0 and + any(r["step"] == step0 and "val_loss" in r for r in log_rows)): + dist.barrier() + since = time.perf_counter() - t0 + step_avg = since / (step - last_val_step) if step > last_val_step else float("nan") + last_val_step = step + training_time += since + v = validate() + log({"step": step, "tokens": step * batch_size, "val_loss": v, + "train_loss": (train_loss / n_loss if n_loss else None), + "train_time_s": training_time, "step_avg_s": step_avg}) + say(f"step {step}/{a.steps} val_loss {v:.5f} train_time {training_time:.0f}s " + f"step_avg {step_avg:.3f}s") + train_loss, n_loss = 0.0, 0 + dist.barrier() + t0 = time.perf_counter() + if step == end: + break + inputs, targets, shard, w0 = next(train_loader) + assert len(inputs) % mbs == 0 + loss_sum = 0.0 + for i in range(len(inputs) // mbs): + xi = inputs[i * mbs:(i + 1) * mbs] + if a.kl_every > 1 and a.head_mode == "scaffold" and i % a.kl_every: + loss = model(xi, targets[i * mbs:(i + 1) * mbs], None) # no KL term on this microbatch + else: + loss = model(xi, targets[i * mbs:(i + 1) * mbs], build_pats(shard, w0 + i * mbs, xi), build_masks(xi)) + loss.backward() + loss_sum += float(loss) if (step + 1) % a.log_every == 0 else 0.0 + for n, p in model.named_parameters(): + assert p.grad is not None, n + dist.all_reduce(p.grad, op=dist.ReduceOp.SUM) + set_hparams(step) + if model.scaffold and model.scaffold_on: + w = a.kl_weight if step < a.kl_until else a.kl_weight * max(0.0, (a.kl_zero_at - step) / max(1, a.kl_zero_at - a.kl_until)) + model.kl_w.fill_(w * a.kl_every) + if step + 1 >= a.kl_zero_at: + model.scaffold_on = False # the penalty is over; the heads train freely + for opt in optimizers: + opt.step() + model.zero_grad(set_to_none=True) + if (step + 1) % a.log_every == 0: + tl = loss_sum / batch_size + train_loss += tl + n_loss += 1 + log({"step": step + 1, "tokens": (step + 1) * batch_size, "train_loss": tl, + "lr_eta": optimizers[1].param_groups[0]["lr"] / optimizers[1].param_groups[0]["initial_lr"], + "train_time_s": training_time + (time.perf_counter() - t0)}) + if (step + 1) % a.save_every == 0 and step + 1 < a.steps: + save_last(step + 1) + if rank0 and a.save_steps and str(step + 1) in a.save_steps.split(","): + torch.save({"model": model.state_dict(), "step": step + 1}, os.path.join(ck_dir, f"step{step + 1}.pt")) + + # ---- final --------------------------------------------------------------------------- + evals = [r for r in log_rows if "val_loss" in r] + steps_to = {} + for th in THRESHOLDS: + hit = [r["step"] for r in evals if r["val_loss"] < th] + steps_to[str(th)] = hit[0] if hit else None + final_val = evals[-1]["val_loss"] + final = {"step": end, "tokens": end * batch_size, "val_loss": final_val, + "train_time_s": training_time, "steps_to_threshold": steps_to, + "track3_rule_single_run": bool((TARGET - final_val) * 1.0 >= 0.004), + "val_at_steps": {str(r["step"]): r["val_loss"] for r in evals}} + if a.stop_at is not None: + final["stopped_at"] = end + say(f"final val_loss {final_val:.5f} after {end} steps and {training_time / 3600:.2f} h; " + f"steps to {TARGET}: {steps_to[str(TARGET)]}") + if rank0: + torch.save({"model": model.state_dict(), "meta": dict(meta, final=final)}, + os.path.join(ck_dir, "final.pt")) + if not a.keep_last and os.path.exists(last_path): + os.remove(last_path) + os.makedirs(os.path.dirname(out_path), exist_ok=True) + with open(out_path, "w") as f: + json.dump(dict(meta, final=final, log=log_rows), f, indent=1) + say(f"wrote {out_path} and {ck_dir}/final.pt") + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/sparsity/code/run_s2_T1024.sh b/sparsity/code/run_s2_T1024.sh new file mode 100644 index 0000000000000000000000000000000000000000..b24ee0244aaf68a9ab8fc958ee140b86305a3a6b --- /dev/null +++ b/sparsity/code/run_s2_T1024.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Length pair for the sparsity axis (SPARSITY_PLAN.md, 2026-10-23): the two 8192-token points whose +# 1024-token twins were never run, at 1024 tokens with the 3250-step track-3 schedule (dense_s0 3.2575): +# every head on the first token plus 31 recent keys (8192: +0.239), and the informed 69 set, 3 heads dense +# (8192: +0.035). mbs 32 keeps the 1024-token rule run under the 80 GB that mbs 64 exceeded in the smoke. +# +# WAIT_FOR=/workspace/s2g_queue.log setsid nohup bash exp/run_s2_T1024.sh > /workspace/s2t_queue.log 2>&1 & +set -u +cd "$(dirname "$0")/.." +TR="torchrun --standalone --nproc_per_node=1" +H=checkpoints/fineweb/heads +mkdir -p results/fineweb logs/fineweb +if [ -n "${WAIT_FOR:-}" ]; then + while [ -f "$WAIT_FOR" ] && ! grep -Eq '^\[queue\] [0-9TZ:-]+ all done$' "$WAIT_FOR"; do sleep 120; done + echo "[queue] $(date -u +%FT%TZ) $WAIT_FOR is done, starting" +fi +run() { # run + local name=$1; shift + if [ -f results/fineweb/f1_$name.json ]; then echo "[queue] $name done, skipping"; return; fi + echo "[queue] $(date -u +%FT%TZ) start $name" + $TR exp/f1_fineweb_train.py --run-name $name --T 1024 --mbs 32 --head-mode index --index-rule sink+recent --index-topk 32 "$@" + echo "[queue] $(date -u +%FT%TZ) end $name rc=$?" +} +run s2_all72_T1024_s0 +run s2_informed69_T1024_s0 --assignments $H/s2_informed69_T8192.json +echo "[queue] $(date -u +%FT%TZ) all done" diff --git a/sparsity/code/run_s2_allocation.sh b/sparsity/code/run_s2_allocation.sh new file mode 100644 index 0000000000000000000000000000000000000000..55c87ed83725483c6adc6513eb34c5870497184c --- /dev/null +++ b/sparsity/code/run_s2_allocation.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Step 1 of SPARSITY_PLAN.md (plan of 2026-10-21): GPT-2 small from random weights on FineWeb at 8192 +# tokens, the 3250-step schedule of dense_T8192_s0, with 25%, 50% or 75% of the heads on the first token +# plus 31 recent keys (weights learned) and the other heads dense. Informed sets take the heads of +# dense_T8192_s0 with the largest attention share inside that window; random sets are a nested uniform +# draw (exp/s2_allocation_sets.py). The 100% point is s1_window32_T8192_s0. +# +# setsid nohup bash exp/run_s2_allocation.sh > /workspace/s2_queue.log 2>&1 & +# +# The last line is "[queue]