11-47 iamseungpil commited on
Commit
3291506
·
0 Parent(s):

Duplicate from iamseungpil/recursive-latent-reasoning

Browse files

Co-authored-by: Seungpil Lee <iamseungpil@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +0 -0
  2. README.md +48 -0
  3. arc/arc-agi_evaluation_challenges.json +0 -0
  4. arc/arc-agi_evaluation_solutions.json +0 -0
  5. arc/arc-agi_test_challenges.json +0 -0
  6. arc/arc-agi_training_challenges.json +0 -0
  7. arc/arc-agi_training_solutions.json +0 -0
  8. archive_ckpt/README.md +13 -0
  9. archive_ckpt/bs24/A_s0.ckpt.pt +3 -0
  10. archive_ckpt/bs24/B_s0.ckpt.pt +3 -0
  11. archive_ckpt/dead_s1000/OFF_s0.ckpt.pt +3 -0
  12. archive_ckpt/dead_s1000/ON_s0.ckpt.pt +3 -0
  13. crystal/train.csv +3 -0
  14. crystal/val.csv +0 -0
  15. lprm_sudoku/README.md +81 -0
  16. lprm_sudoku/SHA256SUMS.txt +7 -0
  17. lprm_sudoku/ckpt/dis_baseline_s0_bestJ.pt +3 -0
  18. lprm_sudoku/ckpt/dis_baseline_s1_bestJ.pt +3 -0
  19. lprm_sudoku/ckpt/dis_baseline_s1_last.pt +3 -0
  20. lprm_sudoku/data/noaug_n9000.pt +3 -0
  21. lprm_sudoku/data/ood_clue17_25.pt +3 -0
  22. lprm_sudoku/data/sudoku_extreme_test1000.pt +3 -0
  23. lprm_sudoku/data/sudoku_extreme_test300.pt +3 -0
  24. lprm_sudoku/ruler/mae_quick.pt +3 -0
  25. sudoku/snapshot.pt +3 -0
  26. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/all_config.yaml +49 -0
  27. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/losses_core.py +341 -0
  28. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/step_10369 +3 -0
  29. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/step_20736 +3 -0
  30. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/trm_a9.py +125 -0
  31. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/all_config.yaml +47 -0
  32. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/losses.py +0 -0
  33. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/step_3000 +3 -0
  34. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/trm_a9.py +112 -0
  35. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/all_config.yaml +47 -0
  36. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/losses.py +0 -0
  37. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/step_3000 +3 -0
  38. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/trm_a9.py +112 -0
  39. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/all_config.yaml +47 -0
  40. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/losses.py +0 -0
  41. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/step_3000 +3 -0
  42. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/trm.py +523 -0
  43. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/all_config.yaml +47 -0
  44. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/losses.py +0 -0
  45. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/step_3000 +3 -0
  46. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/trm.py +523 -0
  47. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/all_config.yaml +47 -0
  48. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/losses.py +0 -0
  49. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/step_3000 +3 -0
  50. trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/trm_a9.py +125 -0
.gitattributes ADDED
The diff for this file is too large to render. See raw diff
 
README.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - other
5
+ tags:
6
+ - reasoning
7
+ - crystal-generation
8
+ - inverse-design
9
+ - sudoku
10
+ - arc-agi
11
+ pretty_name: Recursive Latent Reasoning
12
+ ---
13
+
14
+ # Recursive Latent Reasoning — datasets
15
+
16
+ Data for the **Recursive Latent Reasoning** project: one shared recursive generator
17
+ (a TRM-style weight-tied block refining a VAE latent canvas, with a frozen multi-scale
18
+ MAE as the feature ruler) applied to three tasks.
19
+
20
+ | domain | unit | input → target | objective |
21
+ |---|---|---|---|
22
+ | `crystal/` | a SLICES row | target band_gap → a valid crystal | MAE-based generation, **2 arms**: plain vs **GFN multi-reward** |
23
+ | `sudoku/` | a (puzzle, solution) pair | puzzle → its **unique** solution | unique-solution MAE objective |
24
+ | `arc/` | an ARC task | demo pairs → held-out test output | per-task test-time, unique-solution MAE objective |
25
+
26
+ ## Contents
27
+
28
+ - **`crystal/{train,val}.csv`** — 82,408 / 9,099 rows. Columns:
29
+ `SLICES, formation_energy_per_atom, band_gap, e_above_hull, crystal_system`.
30
+ `band_gap` + `e_above_hull` are the labels the GFN multi-reward uses
31
+ (`R = valid · exp(−β_s·e_hull) · exp(−β_g·|band_gap−c|) · novelty`). SLICES strings
32
+ decode to pymatgen structures.
33
+ - **`sudoku/snapshot.pt`** — `{train,val}.{puzzles,solutions}` long tensors `[N,9,9]`
34
+ (0 = blank, 1–9). Puzzles are dug so each has a **unique** solution; train/val use
35
+ disjoint solution draws. Regenerable at any scale via `latent_reasoning.data.sudoku`.
36
+ - **`arc/arc-agi_*.json`** — the official ARC-AGI-1 training/evaluation/test
37
+ challenges + solutions (400 + 400 tasks; grids 1×30, palette 0–9; output size may
38
+ differ from input).
39
+
40
+ ## Reproduce
41
+
42
+ ```bash
43
+ python -m latent_reasoning.data.prepare_all \
44
+ --crystal-train train.csv --crystal-val val.csv \
45
+ --arc-src <arc_json_dir> --stage ./staging --upload
46
+ ```
47
+
48
+ Crystal data is from the MatterGPT SLICES corpus; ARC-AGI-1 is by Chollet et al.
arc/arc-agi_evaluation_challenges.json ADDED
The diff for this file is too large to render. See raw diff
 
arc/arc-agi_evaluation_solutions.json ADDED
The diff for this file is too large to render. See raw diff
 
arc/arc-agi_test_challenges.json ADDED
The diff for this file is too large to render. See raw diff
 
arc/arc-agi_training_challenges.json ADDED
The diff for this file is too large to render. See raw diff
 
arc/arc-agi_training_solutions.json ADDED
The diff for this file is too large to render. See raw diff
 
archive_ckpt/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `archive_ckpt` — git 에서 제외한 체크포인트 (2026-08-18)
2
+
3
+ `.gitignore` 때문이 아니라 **크기 때문에** git 에서 뺀 가중치다(각 31M).
4
+ 같은 디렉터리의 결과·INTENT json 은 **git 저장소에 있다** —
5
+ `autoresearch/klmdl-260811/bs24/` · `autoresearch/qrank-260810/dead_s1000/`.
6
+
7
+ | 묶음 | 무엇 | 왜 남기나 |
8
+ |---|---|---|
9
+ | `bs24/` | `klmdl-260811` 의 **bs 24** 시절 팔(A·B) | ★런처가 bs 24 → 32 로 바뀌기 **전**의 상태다. 그 인하는 `C-206` 에서 고친 `no_grad` 버그의 OOM 회피였고, 그 때문에 **기준선을 반토막 낸 채 판정**해 왔다. 그 «반토막 난 기준선» 자체가 이 체크포인트다 |
10
+ | `dead_s1000/` | `qrank-260810` 의 폐기된 s1000 계열(OFF·ON) | 판정이 닫힌 팔. 재현 요청 대비 |
11
+
12
+ ⛔둘 다 **죽은 단계**다. 새 실험의 출발점으로 쓰지 마라.
13
+ 살아 있는 이어달리기 꾸러미는 `lprm_sudoku/` 다.
archive_ckpt/bs24/A_s0.ckpt.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80bebbeaa881c48fab3eeae967af59d6283c5528f01f93dceae34b4b38cfcebd
3
+ size 31176407
archive_ckpt/bs24/B_s0.ckpt.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94d11791281c02aaa838e6c1dc0a91c155ce592fd79b8265ebe843a4e72d72d8
3
+ size 31169431
archive_ckpt/dead_s1000/OFF_s0.ckpt.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d2bc4ab0319b732be74f49a28a38b902e7870338717b1bb1c22a7f836607a04
3
+ size 31169427
archive_ckpt/dead_s1000/ON_s0.ckpt.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:171866971d6b29f052010fc348bbf7baa2f810f67cabdab49c6c345f80c5c380
3
+ size 31169397
crystal/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e90ac10f87c7c664994ed519d1ef97187994026cb3b834eabec36bfb5f6e819
3
+ size 36535158
crystal/val.csv ADDED
The diff for this file is too large to render. See raw diff
 
lprm_sudoku/README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `lprm_sudoku` — 무증강 재귀 추론 이어달리기 꾸러미 (2026-08-18)
2
+
3
+ **git 저장소 `MatterGPT_RL` (브랜치 `gram-drift-gflownet-plan`) 이 나르지 못하는 것만** 담았다.
4
+ `.gitignore` 가 `runs/`·`*.log` 를 막고, 학습·평가 데이터는 애초에 미추적이다.
5
+ ⇒ **코드·대장·사전등록·결과 json 은 git 에**, **가중치와 데이터는 여기에** 있다.
6
+
7
+ ## 왜 이 꾸러미가 존재하나
8
+
9
+ `ckpt/dis_baseline_s1_bestJ.pt` 와 `ckpt/dis_baseline_s1_last.pt` 는
10
+ ★**증강 없이 스도쿠를 완전히 푼 체크포인트**다. `ood_clue17_25` 300문제 기준:
11
+
12
+ | 체크포인트 | N | 완전해결 | 푼 퍼즐 | `J_closed` |
13
+ |---|---|---|---|---|
14
+ | `dis_baseline_s1_bestJ.pt` | 32 | 1 (0.0312) | #26 | 0.0764 |
15
+ | `dis_baseline_s1_bestJ.pt` | **300** | **2 (0.0067)** | #26, #42 | 0.0420 |
16
+ | `dis_baseline_s0_bestJ.pt` | 300 | 0 (0.0000) | — | 0.0407 |
17
+ | ★`dis_baseline_s1_last.pt` | **300** | **2 (0.0067)** | #274, #288 | 0.0386 |
18
+
19
+ 푼 4개는 빈칸 55~57칸으로 **평균 난이도**다(전체 평균 56.47). 그중 **#26 과 #274 는
20
+ 이 저장소의 고전 규칙전파 기준선(naked+hidden single, 128/300)이 풀지 못한다.**
21
+
22
+ 검증된 것: `acc_final = 1.000000`(최종 격자 == 정답, 반례 0) · `n_commit == n_blank` ·
23
+ 커밋에 정답 미유입(심는 값은 모델 예측 `cv`, 정답 `cs` 는 채점 전용) · 증강 코드 0건.
24
+
25
+ ### ⚠이 수를 읽을 때 반드시 함께 볼 것
26
+
27
+ - ★**`bestJ` 는 평가셋 앞 32개의 `J_closed` 로 고른 체크포인트다.** `#26` 이 그 32개 안에
28
+ 있으므로 **`bestJ` 의 `#26` 은 순환논증이다.** 선택 편향이 **없는** 증거는
29
+ `dis_baseline_s1_last.pt`(마지막 걸음, 고르지 않음)의 **2/300** 하나다.
30
+ - ⚠**시드 효과를 주장할 수 없다.** 2/300 의 95% 구간 ≈ [0.08%, 2.4%], 0/300 의 상한 ≈ 1%
31
+ ⇒ 시드 0 과 1 은 **통계적으로 구별되지 않는다**.
32
+ - ⚠평가 절차 `closed_loop` 의 정지 조건은 손코딩 스도쿠 모순 탐지기다. 다만 `solved` 는
33
+ *첫 오답 전* 맞은 칸 기준이라 조기 정지는 점수를 **깎기만** 하며 완전해결을 만들지 못한다.
34
+ - ⛔**우열을 주장하지 않는다.** 고전 규칙전파는 128/300 으로 훨씬 위에 있다.
35
+ - ⛔기전·일반 풀이능력·ARC 전이를 주장하지 않는다. 관측은 «드물지만 0 이 아닌 사건»이다.
36
+
37
+ 판정 전문과 반증 이력은 git 저장소 `records/CLAIMS.md` **C-228** 에 있다(적대 검토 포함).
38
+
39
+ ## 무엇이 들었나
40
+
41
+ ```
42
+ data/noaug_n9000.pt 학습 퍼즐 9000개 — ★증강 없음(고정 집합)
43
+ data/ood_clue17_25.pt 평가셋 (val 300)
44
+ data/sudoku_extreme_test300.pt 평가셋 (val 300)
45
+ ruler/mae_quick.pt 동결된 자(SudokuMAE) — ⛔학습에만, 추론엔 안 쓴다
46
+ ckpt/dis_baseline_s0_bestJ.pt 시드 0 · step 미상 · 0/300
47
+ ckpt/dis_baseline_s1_bestJ.pt ★시드 1 · step 9000 · 2/300
48
+ ckpt/dis_baseline_s1_last.pt 시드 1 · 마지막 걸음
49
+ SHA256SUMS.txt
50
+ ```
51
+
52
+ ## 다른 서버에서 이어 하는 법
53
+
54
+ ```bash
55
+ git clone <MatterGPT_RL> && cd MatterGPT_RL
56
+ git checkout gram-drift-gflownet-plan
57
+ huggingface-cli download iamseungpil/recursive-latent-reasoning \
58
+ --repo-type dataset --include 'lprm_sudoku/*' --local-dir /tmp/bundle
59
+
60
+ mkdir -p amlt_data latent_reasoning/faithful/runs/sudoku \
61
+ axes/lprm_sudoku/runs/s0_conv_0813_2355
62
+ cp /tmp/bundle/lprm_sudoku/data/*.pt amlt_data/
63
+ cp /tmp/bundle/lprm_sudoku/ruler/*.pt latent_reasoning/faithful/runs/sudoku/
64
+ cp /tmp/bundle/lprm_sudoku/ckpt/*.pt axes/lprm_sudoku/runs/s0_conv_0813_2355/
65
+
66
+ sha256sum -c /tmp/bundle/lprm_sudoku/SHA256SUMS.txt # ★무결성
67
+ ```
68
+
69
+ `axes/lprm_sudoku/lprm/closed.py:63` 의 `CKPT` 절대경로 **한 줄**만 새 경로로 고치면 된다.
70
+
71
+ **환경**: torch 2.12.0+cu130 · A100 80GB PCIe · python 3.11 (`conda env gram`).
72
+ **불변식**: `latent_reasoning/faithful/gram.py` sha1 = `c85b1f47e838e9f89ba346228f85d1f3f110a2ae`.
73
+ 이 값이 다르면 여기의 어떤 수도 비교 불가다(코드가 매 실행 검사한다).
74
+
75
+ ## 재현
76
+
77
+ ```bash
78
+ python axes/lprm_sudoku/… # 사전등록: autoresearch/exact-260818/PREREG_X1.md
79
+ # 결과: autoresearch/exact-260818/X1.json
80
+ ```
81
+ 판정은 git 저장소 `records/CLAIMS.md` 의 **C-228** 에 있다.
lprm_sudoku/SHA256SUMS.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ 6d2340d1255e87922ff0d269d216196cc80de337c74beb61dbb92aa4453a7b11 lprm_sudoku/ckpt/dis_baseline_s0_bestJ.pt
2
+ fd8b7c59f2b064f0e7c96a04c81c17d79b86e2b086b6e005906dd266c6bfbee6 lprm_sudoku/ckpt/dis_baseline_s1_bestJ.pt
3
+ 2d292074dd6fd43ea999451c5bedde62c3e236bacc87b06877c6d2b75c928941 lprm_sudoku/ckpt/dis_baseline_s1_last.pt
4
+ 4faf48e36a1140bbc3e12d2055cb30792b2cbab390e2d58b37a6c2dccbc5870c lprm_sudoku/data/noaug_n9000.pt
5
+ 00f974ee4169758a82abfb0d3fb6fc3fd3db483bdbe63df0d0a4ce2d9be575f7 lprm_sudoku/data/ood_clue17_25.pt
6
+ fa606cb222d1439f868a216cc5cc677d72c87f9ca9c28de4719f61ecd0d02e4b lprm_sudoku/data/sudoku_extreme_test300.pt
7
+ fa4785aeceea8ae35bc3b1cf3834d9c45078c2ab0797be0b488ea01bc80b83c7 lprm_sudoku/ruler/mae_quick.pt
lprm_sudoku/ckpt/dis_baseline_s0_bestJ.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d2340d1255e87922ff0d269d216196cc80de337c74beb61dbb92aa4453a7b11
3
+ size 31193290
lprm_sudoku/ckpt/dis_baseline_s1_bestJ.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd8b7c59f2b064f0e7c96a04c81c17d79b86e2b086b6e005906dd266c6bfbee6
3
+ size 31193290
lprm_sudoku/ckpt/dis_baseline_s1_last.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d292074dd6fd43ea999451c5bedde62c3e236bacc87b06877c6d2b75c928941
3
+ size 31193259
lprm_sudoku/data/noaug_n9000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4faf48e36a1140bbc3e12d2055cb30792b2cbab390e2d58b37a6c2dccbc5870c
3
+ size 14266821
lprm_sudoku/data/ood_clue17_25.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00f974ee4169758a82abfb0d3fb6fc3fd3db483bdbe63df0d0a4ce2d9be575f7
3
+ size 392601
lprm_sudoku/data/sudoku_extreme_test1000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d1c6cc3a3b074c10fa158b297aab045056cd1c7840c5fb4950da9bd5137c948
3
+ size 1298213
lprm_sudoku/data/sudoku_extreme_test300.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa606cb222d1439f868a216cc5cc677d72c87f9ca9c28de4719f61ecd0d02e4b
3
+ size 391197
lprm_sudoku/ruler/mae_quick.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa4785aeceea8ae35bc3b1cf3834d9c45078c2ab0797be0b488ea01bc80b83c7
3
+ size 42570447
sudoku/snapshot.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:624f585c6ce3c47783978acf6252157618c4496ac4fbc022d602e5e16f050dd6
3
+ size 2853671
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/all_config.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ act_halt: false
7
+ expansion: 4
8
+ forward_dtype: bfloat16
9
+ halt_exploration_prob: 0.1
10
+ halt_max_steps: 16
11
+ hidden_size: 128
12
+ loss:
13
+ ce_ramp: true
14
+ loss_type: stablemax_cross_entropy
15
+ name: losses_core@SelfDistillLossHead
16
+ mlp_t: false
17
+ name: recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9
18
+ no_ACT_continue: true
19
+ num_heads: 4
20
+ pos_encodings: rope
21
+ puzzle_emb_len: 0
22
+ puzzle_emb_ndim: 1280
23
+ beta1: 0.9
24
+ beta2: 0.95
25
+ checkpoint_every_eval: true
26
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0
27
+ data_paths:
28
+ - data/arc1concept-aug-0
29
+ data_paths_test: []
30
+ ema: true
31
+ ema_rate: 0.999
32
+ epochs: 1368
33
+ eval_interval: 171
34
+ eval_save_outputs: []
35
+ evaluators: []
36
+ freeze_weights: false
37
+ global_batch_size: 64
38
+ load_checkpoint: null
39
+ lr: 0.0001
40
+ lr_min_ratio: 1.0
41
+ lr_warmup_steps: 2000
42
+ min_eval_interval: 0
43
+ project_name: Arc1concept-aug-0-ACT-torch
44
+ puzzle_emb_lr: 0.0014
45
+ puzzle_emb_weight_decay: 0.1
46
+ run_name: trm_arc1_a9_walk_elr_s0
47
+ sam_rho: 0.0
48
+ seed: 0
49
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/losses_core.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """losses_core.py -- the LIVE subset of TRM models/losses.py, copied verbatim.
2
+
3
+ Contains only what the live queue and the surviving Q2 claims need: the stablemax helpers, ACTLossHead (the baseline every
4
+ claim is measured against; its loss is split into act_loss() with an optional per-row CE weight -- row_w=None is the verbatim
5
+ computation, smoke_core (a)), certify() (the sound Sudoku certifier, still imported by core/_meta_rejected/losses_meta.py) and
6
+ SelfDistillLossHead as the queue trains it since §2cd: the walk's segment CE ramp (ce_ramp, WALK) and §2cm R3c's output-level
7
+ unlikelihood of the model's own non-converged answers (unlik / w_ul), and §2ct's LOOLossHead (leave-one-demonstration-out task-embedding
8
+ slots, LOOSparseEmbedding) on top of it. The dead exploratory heads and flags (C-Q2-04/05/12/13/
9
+ 20/43/44/59/60/81..84/96; the §2by order/hint/Δz/NCE line, C-Q2-118..124; the hyper/z-bits arms) were removed earlier; PREREG
10
+ §2cs archived the §2az/§2bz trajectory-JEPA head TrajWindowDistillLossHead, wrong_row_mask, tc_first_fixed and the §2cc-§2ci
11
+ SelfDistillLossHead terms (teacher-dump KL / latent / fixed-point pulls, Drift) in _archive/core_closed/core/models/
12
+ losses_core_closed.py; git history and _archive/ are their record.
13
+ """
14
+ from typing import Any, Tuple, Dict, Sequence, Optional
15
+
16
+ import os
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from models.sparse_embedding import CastedSparseEmbedding
22
+
23
+ IGNORE_LABEL_ID = -100
24
+
25
+
26
+ def s(x, epsilon=1e-30):
27
+ return torch.where(
28
+ x<0,
29
+ 1/(1-x+ epsilon),
30
+ x + 1
31
+ )
32
+
33
+
34
+ def log_stablemax(x, dim=-1):
35
+ s_x = s(x)
36
+ return torch.log(s_x/torch.sum(s_x, dim=dim, keepdim=True))
37
+
38
+
39
+ def stablemax_cross_entropy(logits, labels, ignore_index: int = -100, valid_mask=None):
40
+ logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
41
+
42
+ if valid_mask is None:
43
+ valid_mask = (labels != ignore_index)
44
+ transformed_labels = torch.where(valid_mask, labels, 0)
45
+ prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
46
+
47
+ return -torch.where(valid_mask, prediction_logprobs, 0)
48
+
49
+
50
+ class ACTLossHead(nn.Module):
51
+ def __init__(self, model: nn.Module, loss_type: str):
52
+ super().__init__()
53
+ self.model = model
54
+ self.loss_fn = globals()[loss_type]
55
+
56
+ def initial_carry(self, *args, **kwargs):
57
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
58
+
59
+ def forward(
60
+ self,
61
+ return_keys: Sequence[str],
62
+ # Model args
63
+ **model_kwargs,
64
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
65
+ # Model logits
66
+ # B x SeqLen x D
67
+ new_carry, outputs = self.model(**model_kwargs)
68
+ return self.act_loss(return_keys, new_carry, outputs)
69
+
70
+ def act_loss(self, return_keys: Sequence[str], new_carry, outputs: Dict[str, torch.Tensor], row_w: Optional[torch.Tensor] = None):
71
+ """The ACT loss of one segment's outputs; row_w [B] (optional) weighs each row's mean CE (§2cd ce_ramp)."""
72
+ labels = new_carry.current_data["labels"]
73
+
74
+ with torch.no_grad():
75
+ # Preds
76
+ outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
77
+
78
+ # Correctness
79
+ mask = (labels != IGNORE_LABEL_ID)
80
+ loss_counts = mask.sum(-1)
81
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
82
+
83
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
84
+ seq_is_correct = is_correct.sum(-1) == loss_counts
85
+
86
+ # Metrics (halted)
87
+ valid_metrics = new_carry.halted & (loss_counts > 0)
88
+ metrics = {
89
+ "count": valid_metrics.sum(),
90
+
91
+ "accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
92
+ "exact_accuracy": (valid_metrics & seq_is_correct).sum(),
93
+
94
+ "q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
95
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
96
+ }
97
+
98
+ # Losses
99
+
100
+ lm_loss = self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask) / loss_divisor
101
+ lm_loss = (lm_loss if row_w is None else lm_loss * row_w.unsqueeze(-1)).sum()
102
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
103
+ metrics.update({
104
+ "lm_loss": lm_loss.detach(),
105
+ "q_halt_loss": q_halt_loss.detach(),
106
+ })
107
+ # Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
108
+ q_continue_loss = 0
109
+ if "target_q_continue" in outputs:
110
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
111
+
112
+ metrics["q_continue_loss"] = q_continue_loss.detach()
113
+ # Filter outputs for return
114
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
115
+
116
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
117
+
118
+
119
+ _SUD_CELL = torch.arange(81)
120
+ _SUD_ROW, _SUD_COL = _SUD_CELL // 9, _SUD_CELL % 9
121
+ _SUD_BOX = (_SUD_CELL // 9 // 3) * 3 + (_SUD_CELL % 9 // 3)
122
+
123
+
124
+ def certify(pred_tok: torch.Tensor, inp_tok: torch.Tensor) -> torch.Tensor:
125
+ """Sound Sudoku certifier -- the same function as probes/star_certify.py::certify, but run
126
+ on whatever device `pred_tok` lives on (the training loop is on CUDA).
127
+
128
+ pred_tok/inp_tok: [B,81] token ids (blank = 1, digit d -> d+1). Returns bool [B]:
129
+ True iff the prediction is a complete legal grid that also preserves every clue. Because
130
+ Sudoku-Extreme puzzles are uniquely solvable, acceptance is equivalent to correctness --
131
+ so this reads no label, yet it is a gold-quality signal.
132
+ """
133
+ dev = pred_tok.device
134
+ d = pred_tok.long() - 1 # digits 1..9, junk otherwise
135
+ good = ((d >= 1) & (d <= 9)).all(-1)
136
+ B = d.shape[0]
137
+ oh = torch.zeros(B, 81, 10, dtype=torch.int32, device=dev)
138
+ oh.scatter_(2, d.clamp(0, 9).unsqueeze(-1), 1)
139
+ for ids in (_SUD_ROW, _SUD_COL, _SUD_BOX):
140
+ s = torch.zeros(B, 9, 10, dtype=torch.int32, device=dev).index_add_(1, ids.to(dev), oh)
141
+ good = good & (s[:, :, 1:] == 1).all(-1).all(-1) # every unit is a permutation
142
+ clue = inp_tok > 1
143
+ good = good & ((pred_tok == inp_tok) | ~clue).all(-1) # clues untouched
144
+ return good
145
+
146
+
147
+ UL_FIELDS = ("neg", "n_neg") # §2cm teacher_dump.py certify: per converged row, its <= M non-converged answers != its label
148
+ _TD: Dict[str, Dict[str, Any]] = {} # certify dir -> {field: tensor on the training device, "K": its M}
149
+
150
+
151
+ def _td(path: str, device, fields: Sequence[str]) -> Dict[str, Any]:
152
+ """The dir's `fields` (+ meta's K), each loaded once per process straight to the device; a missing field is a clear error."""
153
+ d = _TD.setdefault(path, {})
154
+ miss = [k for k in fields if k not in d]
155
+ if miss or "K" not in d:
156
+ import json, numpy as np
157
+ for k in miss:
158
+ f = os.path.join(path, k + ".npy")
159
+ if not os.path.exists(f):
160
+ raise FileNotFoundError(f"dump {path} has no {k}.npy, which the enabled terms need ({', '.join(fields)})")
161
+ d[k] = torch.from_numpy(np.load(f)).to(device)
162
+ d["K"] = int(json.load(open(os.path.join(path, "meta.json")))["K"])
163
+ return d
164
+
165
+
166
+ class SelfDistillLossHead(ACTLossHead):
167
+ """§2cd walk + §2cm R3c; ce_ramp False and w_ul 0 is ACTLossHead to the bit (smoke_core (p)), and every configuration == the
168
+ pre-§2cs head (git 0c7f88a, which also held the §2cc-§2ci dump / Drift terms) to the bit (smoke_core (V)).
169
+
170
+ ce_ramp (§2cd N0r, the queue's WALK, with or without unlik): row CE weight w_s = 2 s / (H + 1), s = new_carry.steps (1..H, the
171
+ walk's stagger included), H = halt_max_steps: a FIXED weight per segment (mean 1 over s = 1..H), never
172
+ renormalised over the batch.
173
+ §2cm w_ul: on `unlik` (a teacher_dump.py certify dir; row_uid = the row of its neg / n_neg, < 0 = a gold row: skipped), rows
174
+ with n_neg > 0: the mean over the (negative m < n_neg, cell where neg_m != the row's label) pairs of
175
+ -log(1 - p(neg_m's digit)), p = the CE's stablemax (float64), times the row's ce_ramp weight (1 without the ramp),
176
+ summed over rows like the CE.
177
+ The certify dir lives in the module-level _TD (keyed by its path), never on the head: pretrain's EMA / checkpoint
178
+ copy.deepcopy(head) copies a string; its neg / n_neg are loaded once, on the device. The slices are fetched BEFORE the model
179
+ call (_targets, eager) by the ACT wrapper's own rule for which row / segment each slot holds after it, so model + loss stay one
180
+ compiled graph: a graph break AFTER the model call fails the compiled backward (inductor gets None tangents for the unused
181
+ outputs). With grad disabled (pretrain.evaluate, trm_tta) the loss is the plain ACT loss.
182
+ Metrics (x count, as pretrain divides them by it): ul = the term's row sum / batch rows; ul_rows = the rows it touched this call.
183
+ """
184
+
185
+ def __init__(self, model: nn.Module, loss_type: str, ce_ramp: bool = False, unlik: str = "", w_ul: float = 0.0):
186
+ super().__init__(model, loss_type)
187
+ self.ce_ramp, self.unlik, self.w_ul = bool(ce_ramp), str(unlik), float(w_ul)
188
+ assert bool(self.unlik) == (self.w_ul > 0), "unlik (a certify dir) goes with w_ul > 0, only"
189
+
190
+ def forward(self, return_keys: Sequence[str], **model_kwargs):
191
+ train = torch.is_grad_enabled()
192
+ tg = self._targets(model_kwargs["carry"], model_kwargs["batch"]) if self.unlik and train else None
193
+ new_carry, outputs = self.model(**model_kwargs)
194
+ row_w = None
195
+ if self.ce_ramp and train:
196
+ row_w = 2 * new_carry.steps.to(torch.float64) / (self.model.config.halt_max_steps + 1)
197
+ new_carry, loss, metrics, detached, all_halted = self.act_loss(return_keys, new_carry, outputs, row_w)
198
+ if tg is not None:
199
+ loss = self._unlik(loss, new_carry, outputs, metrics, tg, row_w)
200
+ return new_carry, loss, metrics, detached, all_halted
201
+
202
+ @staticmethod
203
+ def unlik_term(logits, labels, neg, keep):
204
+ """[B]: per row, the mean over the (negative m with keep[m], cell where neg_m != the label, label not ignored) pairs of
205
+ -log(1 - p(neg_m's digit)), p = stablemax(logits) in float64 as the CE; 0 without a pair. Computed as log S - log(S - s_neg)
206
+ (S = the stablemax numerators' sum, S - s_neg > 0: finite, no 1 - p cancellation)."""
207
+ sx = s(logits.to(torch.float64)) # [B, L, V]
208
+ tot = sx.sum(-1).unsqueeze(1) # [B, 1, L]
209
+ sn = sx.unsqueeze(1).expand(-1, neg.shape[1], -1, -1).gather(-1, neg.long().unsqueeze(-1)).squeeze(-1) # [B, M, L]
210
+ m = keep.unsqueeze(-1) & (neg != labels.unsqueeze(1)) & (labels != IGNORE_LABEL_ID).unsqueeze(1)
211
+ return torch.where(m, torch.log(tot) - torch.log(tot - sn), 0).sum((1, 2)) / m.sum((1, 2)).clamp_min(1)
212
+
213
+ @torch.compiler.disable
214
+ def _targets(self, carry, batch) -> Dict[str, torch.Tensor]:
215
+ """Each slot's certify-dir slices for THIS call: a halted slot takes the batch's row, the others keep theirs (the ACT wrapper's
216
+ rule); row mask + negatives on the device."""
217
+ h = carry.halted
218
+ uid = torch.where(h.view(-1, 1), batch["row_uid"].view(h.shape[0], -1), carry.current_data["row_uid"].view(h.shape[0], -1))
219
+ uid = uid[:, 0].long()
220
+ ul = _td(self.unlik, h.device, UL_FIELDS)
221
+ assert int(uid.max()) < ul["neg"].shape[0], "row_uid beyond the certify dir's negatives"
222
+ u = uid.clamp_min(0)
223
+ nn_ = ul["n_neg"][u]
224
+ return {"ul_m": (uid >= 0) & (nn_ > 0), "ul_neg": ul["neg"][u], "ul_k": torch.arange(ul["neg"].shape[1], device=h.device) < nn_.unsqueeze(-1)}
225
+
226
+ def _unlik(self, loss, new_carry, outputs, metrics, t, row_w=None):
227
+ cntf = metrics["count"].clamp_min(1).to(torch.float32)
228
+ ul = self.unlik_term(outputs["logits"], new_carry.current_data["labels"], t["ul_neg"], t["ul_k"])
229
+ v = torch.where(t["ul_m"], ul if row_w is None else ul * row_w, 0)
230
+ metrics["ul"] = v.detach().sum().to(torch.float32) / outputs["z_H"].shape[0] * cntf
231
+ metrics["ul_rows"] = t["ul_m"].sum().to(torch.float32) * cntf
232
+ return loss + self.w_ul * v.sum()
233
+
234
+
235
+ def loo_rows(ds: str):
236
+ """§2ct: the rows of <ds>/train -> (inputs [n, seq], pid [n], j [n] = the row's index among its task's demonstrations, K [n] = the
237
+ task's demonstration count), numpy int64 but the inputs; one puzzle per identifier (no augmentation) asserted."""
238
+ import numpy as np
239
+ a = {k: np.load(f"{ds}/train/all__{k}.npy") for k in ("inputs", "puzzle_identifiers", "puzzle_indices")}
240
+ ids, pi = a["puzzle_identifiers"], a["puzzle_indices"]
241
+ assert len(np.unique(ids)) == len(ids) and pi[-1] == len(a["inputs"]), f"{ds}/train: one puzzle per identifier (no augmentation)"
242
+ q = np.searchsorted(pi, np.arange(len(a["inputs"])), side="right") - 1
243
+ return a["inputs"], ids[q].astype(np.int64), (np.arange(len(q)) - pi[q]).astype(np.int64), np.diff(pi)[q].astype(np.int64)
244
+
245
+
246
+ class LOOSparseEmbedding(CastedSparseEmbedding):
247
+ """§2ct: the task table widened to S slots per task (row pid * S + s: slot 0 = fitted on every demonstration, slot j + 1 = on all but
248
+ demonstration j), initialised with the task's row in every slot, and the parent's three buffers in its order (weights, local_weights,
249
+ local_ids: pretrain's SignSGD is unchanged). An id >= R (= the rows) reads row id - R DETACHED: that row's local gradient is exactly 0,
250
+ so the SignSGD step gives its table row weight decay only; eval reads rows as the parent (ids >= R too)."""
251
+
252
+ def __init__(self, base: CastedSparseEmbedding, S: int):
253
+ nn.Module.__init__(self)
254
+ self.cast_to = base.cast_to
255
+ self.weights = nn.Buffer(base.weights.repeat_interleave(S, 0), persistent=True)
256
+ self.local_weights = nn.Buffer(base.local_weights, persistent=False)
257
+ self.local_ids = nn.Buffer(base.local_ids, persistent=False)
258
+
259
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
260
+ R = self.weights.shape[0]
261
+ sg = inputs >= R
262
+ ids = torch.where(sg, inputs - R, inputs)
263
+ if not self.training:
264
+ return self.weights[ids].to(self.cast_to)
265
+ with torch.no_grad():
266
+ self.local_weights.copy_(self.weights[ids])
267
+ self.local_ids.copy_(ids)
268
+ return torch.where(sg.unsqueeze(-1), self.local_weights.detach(), self.local_weights).to(self.cast_to)
269
+
270
+
271
+ _LOO: Dict[str, Dict[str, Any]] = {} # loo_data -> its sorted row keys / j / K (numpy) + per-device copies: never on the head (as _TD)
272
+
273
+
274
+ class LOOLossHead(SelfDistillLossHead):
275
+ """§2ct arm A: leave-one-demonstration-out task-embedding meta-learning on SelfDistillLossHead (the walk's ce_ramp; unlik as there).
276
+ __init__ swaps the model's CastedSparseEmbedding for a LOOSparseEmbedding of S = Kmax + 1 slots (Kmax = the most demonstrations of a
277
+ task in <loo_data>/train; before pretrain hands puzzle_emb.buffers() to SignSGD) and keys every <loo_data>/train row by (its inputs,
278
+ its task) -> (j, K): a task with two equal demonstration inputs, a hash collision or a task of one demonstration is an AssertionError.
279
+ Training (grad enabled): every row gets a role from a private generator seeded with torch.initial_seed() (= pretrain's seed): u < p_score
280
+ -> score: slot j + 1 DETACHED (id + R: only the dense weights learn from the held-out prediction); u < p_score + p_fit0 -> fit0: slot 0;
281
+ else fitLOO: uniform over {1..K} \\ {j + 1}; id' = pid * S + s + R [score]. The ACT wrapper takes id' only for halted rows (a new
282
+ episode), so the carry keeps the role for the episode, and slot j + 1 never gets a gradient from demonstration j. No grad (pretrain's
283
+ evaluate): pid -> pid * S (slot 0). Metrics (x count, as pretrain divides them by it) over the halted score rows: loo_rows = their
284
+ number, loo_exact = their exact fraction, loo_ce = their mean CE (the loss_fn's, per labelled cell)."""
285
+
286
+ def __init__(self, model: nn.Module, loss_type: str, loo_data: str = "", p_score: float = 0.5, p_fit0: float = 0.25, **kw):
287
+ super().__init__(model, loss_type, **kw)
288
+ import numpy as np
289
+ emb = model.inner.puzzle_emb
290
+ assert type(emb) is CastedSparseEmbedding and 0 <= p_score and 0 <= p_fit0 and p_score + p_fit0 <= 1, (type(emb), p_score, p_fit0)
291
+ x, pid, j, K = loo_rows(loo_data)
292
+ N = emb.weights.shape[0]
293
+ assert K.min() >= 2, f"{loo_data}/train: a task of {K.min()} demonstration(s) (no fitLOO slot)"
294
+ assert 0 < pid.min() and pid.max() < N and int(x.max()) * x.shape[1] * N < 1 << 32, f"{loo_data}/train: ids {pid.min()}..{pid.max()} for a {N}-row table"
295
+ assert len(np.unique(np.c_[pid, x], axis=0)) == len(x), f"{loo_data}/train: a task with two equal demonstration inputs"
296
+ w = np.random.default_rng(0).integers(1, 1 << 31, x.shape[1])
297
+ key = (x.astype(np.int64) * w).sum(1) * N + pid
298
+ o = np.argsort(key)
299
+ assert (np.diff(key[o]) > 0).all(), f"{loo_data}/train: a row-key collision"
300
+ _LOO[loo_data] = {"key": key[o], "j": j[o], "K": K[o], "w": w}
301
+ self.loo_data, self.p_score, self.p_fit0, self.seed, self._gen = loo_data, float(p_score), float(p_fit0), torch.initial_seed(), None
302
+ self.N, self.S = N, int(K.max()) + 1
303
+ self.R = N * self.S
304
+ model.inner.puzzle_emb = LOOSparseEmbedding(emb, self.S)
305
+
306
+ def forward(self, return_keys: Sequence[str], **model_kwargs):
307
+ b = model_kwargs["batch"]
308
+ model_kwargs["batch"] = self._remap(b) if torch.is_grad_enabled() else dict(b, puzzle_identifiers=b["puzzle_identifiers"] * self.S)
309
+ return super().forward(return_keys, **model_kwargs)
310
+
311
+ @torch.compiler.disable
312
+ def _remap(self, b: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
313
+ """The batch with every row's id' (class docstring); its (inputs, task) must be a <loo_data>/train row."""
314
+ x, p = b["inputs"], b["puzzle_identifiers"]
315
+ L = _LOO[self.loo_data]
316
+ d = L.get(str(x.device)) or L.setdefault(str(x.device), {k: torch.from_numpy(L[k]).to(x.device) for k in ("key", "j", "K", "w")})
317
+ k = (x.long() * d["w"]).sum(-1) * self.N + p.long()
318
+ i = torch.searchsorted(d["key"], k).clamp_max(d["key"].numel() - 1)
319
+ assert bool((d["key"][i] == k).all()), f"LOOLossHead: a training row that is not a {self.loo_data}/train row"
320
+ j, K = d["j"][i], d["K"][i]
321
+ if self._gen is None or self._gen.device != x.device:
322
+ self._gen = torch.Generator(x.device).manual_seed(self.seed)
323
+ u, v = torch.rand((2, x.shape[0]), generator=self._gen, device=x.device, dtype=torch.float64)
324
+ sc = u < self.p_score
325
+ r = torch.minimum((v * (K - 1)).long(), K - 2) # uniform over 0..K-2
326
+ s = torch.where(sc, j + 1, torch.where(u < self.p_score + self.p_fit0, 0, r + 1 + (r >= j).long()))
327
+ return dict(b, puzzle_identifiers=(p.long() * self.S + s + self.R * sc.long()).to(p.dtype))
328
+
329
+ def act_loss(self, return_keys: Sequence[str], new_carry, outputs: Dict[str, torch.Tensor], row_w: Optional[torch.Tensor] = None):
330
+ r = super().act_loss(return_keys, new_carry, outputs, row_w)
331
+ if torch.is_grad_enabled():
332
+ with torch.no_grad():
333
+ m, lg, y = r[2], outputs["logits"], new_carry.current_data["labels"]
334
+ on = y != IGNORE_LABEL_ID
335
+ sc = new_carry.halted & on.any(-1) & (new_carry.current_data["puzzle_identifiers"] >= self.R)
336
+ n, c = sc.sum().to(torch.float32), m["count"].clamp_min(1).to(torch.float32)
337
+ ce = self.loss_fn(lg, y, ignore_index=IGNORE_LABEL_ID, valid_mask=on).sum(-1) / on.sum(-1).clamp_min(1)
338
+ ok = ((lg.argmax(-1) == y) | ~on).all(-1)
339
+ m.update(loo_rows=n * c, loo_exact=(sc & ok).sum() / n.clamp_min(1) * c,
340
+ loo_ce=torch.where(sc, ce, 0).sum().to(torch.float32) / n.clamp_min(1) * c)
341
+ return r
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/step_10369 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27dffb181af31e6ed8df60900e200f373b4424d9a853a5a0aed09693fb47f6dc
3
+ size 7556469
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/step_20736 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:629762a2ba86b63827264c4ad832fcbca46dbc6afd464e0fde7c730013b1dea5
3
+ size 7556469
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9_walk_elr_s0/trm_a9.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PREREG_Q2 §2cr a9: an ARC TRM body that is exactly equivariant to permutations of colours 1..9 (S9) and invariant to
2
+ where the grid sits on the 30 x 30 canvas.
3
+
4
+ Why: on no-aug ARC the plain body with WALK stops memorising (.94 -> .26 on train demos) but learns no rule and finds no fixed
5
+ points (C-Q2-157); on Sudoku the judge and the self-training rest on an equivariant body (C-Q2-151/152/155). Colour 0 (background)
6
+ stays special -- ARC treats it so -- hence S9, not S10:
7
+ logits(pi . x, pi . e) = pi . logits(x, e) for pi fixing colour 0 (core/tests/smoke_a9.py (a); e = the task table)
8
+
9
+ Tokens: 900 cells x 10 colour slots = 9,000, COLOUR-MAJOR (hidden [B, 10*900, D] == [B, 10, 900, D]), no puzzle prefix. Slot k of
10
+ a cell is embedded from its type w.r.t. colour k (token 2 + k): {pad, EOS, colour == k, another colour}; slot 0 also gets a learned
11
+ background flag. The task embedding is the parent's sparse puzzle_emb (same SignSGD optimiser, lr and weight decay in pretrain.py)
12
+ at width 10 * D, read as one D-vector per colour slot and added to that slot of every cell at every input injection.
13
+ Block (post-norm, the S9Block frame): (i) per-slot attention over the 900 cells, one weight set for all slots, the parent's 1D RoPE
14
+ (the parent's self_attn: mlp_t=false); (ii) + (iii) = S9Block.mix_digits_channels: position-free attention over each cell's 10
15
+ slots, then the channel SwiGLU.
16
+ Output: per cell token 0 (pad) = -1e4, token 1 (EOS) = a linear read of the mean over the 10 slots, token 2 + k = slot k's scalar;
17
+ Q head on the mean over all 9,000 tokens.
18
+ Translation: forward moves each row's INPUT so its first row / column holding a token >= 1 lands on (0, 0) (a cyclic roll; the
19
+ rolled-in cells are pad) and rolls the logits back; the carry and z_H live in the aligned frame. The builder puts a pair's input
20
+ and label at the same offset (all 3,988 arc1concept-aug-0 train rows; 74% are offset), so label cells never wrap, the body is
21
+ exactly translation-invariant (smoke (c)) and the builder's random offsets carry no signal. Everything else (ACT wrapper,
22
+ carry, reset, H/L cycles, no-grad cycles, detach, walk) is the parent trm.py code.
23
+
24
+ arch.name=recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9 with arch.puzzle_emb_ndim = 10 * hidden_size,
25
+ arch.puzzle_emb_len=0, arch.pos_encodings=rope, arch.mlp_t=false; ...@TinyRecursiveReasoningModel_A9S = a9s (§2cr 정정 3 v1), a class
26
+ and not an arch key because the parent's pydantic config drops unknown keys silently.
27
+ """
28
+ import os
29
+ from typing import Dict
30
+
31
+ import torch
32
+
33
+ from models.layers import rms_norm, CastedEmbedding, CastedLinear, RotaryEmbedding
34
+ from models.recursive_reasoning.trm import (
35
+ TinyRecursiveReasoningModel_ACTV1Config, TinyRecursiveReasoningModel_ACTV1ReasoningModule,
36
+ TinyRecursiveReasoningModel_ACTV1_Inner, TinyRecursiveReasoningModel_ACTV1InnerCarry)
37
+ from models.recursive_reasoning.trm_s9 import S9Block, TinyRecursiveReasoningModel_S9
38
+
39
+ N_COL, SIDE = 10, 30 # colour slots (token 2 + k = colour k; 1 = EOS, 0 = pad); the canvas side
40
+
41
+
42
+ def shift(t: torch.Tensor, r: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
43
+ """t [B, 900, ...] -> t' with t'[b, (i, j)] = t[b, ((i + r_b) % 30, (j + c_b) % 30)] (a per-row cyclic roll by (-r_b, -c_b))."""
44
+ B, i = t.shape[0], torch.arange(SIDE, device=t.device)
45
+ rows, cols = ((i + r.view(B, 1)) % SIDE).view(B, SIDE, 1), ((i + c.view(B, 1)) % SIDE).view(B, 1, SIDE)
46
+ return t.view(B, SIDE, SIDE, *t.shape[2:])[torch.arange(B, device=t.device).view(B, 1, 1), rows, cols].view(t.shape)
47
+
48
+
49
+ class A9Block(S9Block):
50
+ """(i) cell attention per colour slot (shared weights, RoPE) -> S9Block's (ii) slot attention + (iii) channel MLP."""
51
+
52
+ def forward(self, cos_sin, hidden_states: torch.Tensor) -> torch.Tensor:
53
+ B, T, D = hidden_states.shape
54
+ h = hidden_states.view(B * N_COL, T // N_COL, D)
55
+ h = rms_norm(h + self.self_attn(cos_sin=cos_sin, hidden_states=h), variance_epsilon=self.norm_eps)
56
+ return self.mix_digits_channels(h.view(B, N_COL, T // N_COL, D))
57
+
58
+
59
+ class A9LMHead(torch.nn.Module):
60
+ """[B, 10*900, D] -> vocab logits [B, 900, 12]: pad -1e4, EOS from the slot mean, token 2 + k from slot k."""
61
+
62
+ def __init__(self, hidden_size: int) -> None:
63
+ super().__init__()
64
+ self.slot, self.eos = CastedLinear(hidden_size, 1, bias=False), CastedLinear(hidden_size, 1, bias=False)
65
+
66
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
67
+ z = z.view(z.shape[0], N_COL, -1, z.shape[-1])
68
+ col = self.slot(z)[..., 0].transpose(1, 2) # [B, 900, 10]
69
+ return torch.cat((col.new_full(col.shape[:2] + (1,), -1e4), self.eos(z.mean(1)), col), dim=-1)
70
+
71
+
72
+ class TinyRecursiveReasoningModel_A9_Inner(TinyRecursiveReasoningModel_ACTV1_Inner):
73
+ task_raw = False # a9s (§2cr 정정 3 v1): the task vector added after embed_scale, at the table's raw scale
74
+
75
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
76
+ D = config.hidden_size
77
+ assert config.seq_len == SIDE * SIDE and config.vocab_size == N_COL + 2, "a9: ARC only (30 x 30, vocab 12)"
78
+ assert config.puzzle_emb_ndim == N_COL * D and config.puzzle_emb_len == 0 and config.puzzle_emb_mode == "lookup", \
79
+ "a9: puzzle_emb_ndim = 10 * hidden_size (one task vector per colour slot), puzzle_emb_len=0"
80
+ assert config.pos_encodings == "rope" and not config.mlp_t and config.fast_slice is None, "a9: rope, mlp_t=false, no fast slice"
81
+ assert not os.environ.get("SELF_COND"), "a9: SELF_COND is not supported"
82
+ super().__init__(config)
83
+ # the parent sized a ceil(ndim / D) = 10-slot prefix (the wrapper's z_H slice, the output slice, RoPE): a9 has none
84
+ self.puzzle_emb_len = 0
85
+ self.rotary_emb = RotaryEmbedding(dim=D // config.num_heads, max_position_embeddings=config.seq_len, base=config.rope_theta)
86
+ del self.embed_tokens
87
+ self.embed_types = CastedEmbedding(5, D, init_std=1.0 / self.embed_scale, cast_to=self.forward_dtype) # 4 types + bg flag
88
+ self.lm_head = A9LMHead(D)
89
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[A9Block(config) for _i in range(config.L_layers)])
90
+
91
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, prev_pred=None, ctx=None):
92
+ # slot k's type at a cell: 0 pad, 1 EOS, 2 colour == k, 3 another colour; row 4 of the table = slot 0's background flag
93
+ x, k = input.unsqueeze(1), torch.arange(2, 2 + N_COL, device=input.device).view(1, N_COL, 1)
94
+ types = torch.where(x < 2, x, torch.where(x == k, 2, 3)).to(torch.int32) # [B, 10, 900]
95
+ bg = (k == 2).unsqueeze(-1) * self.embed_types.embedding_weight[4].to(self.forward_dtype) # [1, 10, 1, D]
96
+ task = self.puzzle_emb(puzzle_identifiers).view(-1, N_COL, 1, self.config.hidden_size)
97
+ e = self.embed_types(types) + bg
98
+ return (self.embed_scale * e + task if self.task_raw else self.embed_scale * (e + task)).flatten(1, 2)
99
+
100
+ def empty_carry(self, batch_size: int):
101
+ shape = (batch_size, N_COL * self.config.seq_len, self.config.hidden_size)
102
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=torch.empty(shape, dtype=self.forward_dtype),
103
+ z_L=torch.empty(shape, dtype=self.forward_dtype))
104
+
105
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]):
106
+ x = batch["inputs"]
107
+ g = (x >= 1).view(-1, SIDE, SIDE)
108
+ r0, c0 = g.any(2).int().argmax(1), g.any(1).int().argmax(1) # the anchor; (0, 0) for an all-pad row
109
+ new_carry, out, _, z_H = super().forward(carry, dict(batch, inputs=shift(x, r0, c0)))
110
+ q_logits = self.q_head(z_H.mean(dim=1)).to(torch.float32) # permutation-invariant Q (s9's)
111
+ return new_carry, shift(out, -r0, -c0), (q_logits[..., 0], q_logits[..., 1]), z_H
112
+
113
+
114
+ class TinyRecursiveReasoningModel_A9(TinyRecursiveReasoningModel_S9):
115
+ """ACT wrapper driving the a9 inner (§2cr)."""
116
+ inner_cls = TinyRecursiveReasoningModel_A9_Inner
117
+
118
+
119
+ class TinyRecursiveReasoningModel_A9S_Inner(TinyRecursiveReasoningModel_A9_Inner):
120
+ task_raw = True
121
+
122
+
123
+ class TinyRecursiveReasoningModel_A9S(TinyRecursiveReasoningModel_A9):
124
+ """a9s: the input embedding embed_scale * (types + bg) + task (a9: embed_scale * (types + bg + task)), the table at its raw scale."""
125
+ inner_cls = TinyRecursiveReasoningModel_A9S_Inner
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/all_config.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 128
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9
16
+ no_ACT_continue: true
17
+ num_heads: 4
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 0
20
+ puzzle_emb_ndim: 1280
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0
25
+ data_paths:
26
+ - data/arc_a9p1
27
+ data_paths_test: []
28
+ ema: true
29
+ ema_rate: 0.999
30
+ epochs: 1422
31
+ eval_interval: 1422
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 64
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 200
40
+ min_eval_interval: 0
41
+ project_name: Arc1concept-aug-0-ACT-torch
42
+ puzzle_emb_lr: 0.01
43
+ puzzle_emb_weight_decay: 0.1
44
+ run_name: trm_arc1_a9p1_s0
45
+ sam_rho: 0.0
46
+ seed: 0
47
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/losses.py ADDED
The diff for this file is too large to render. See raw diff
 
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/step_3000 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:371eedbf8a5cf6a27657202fdc0a85b3dc90b6d4a03dfb36d629a008aeac8f33
3
+ size 7556443
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1_s0/trm_a9.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PREREG_Q2 §2cr a9: an ARC TRM body that is exactly equivariant to permutations of colours 1..9 (S9) and invariant to
2
+ where the grid sits on the 30 x 30 canvas.
3
+
4
+ Why: on no-aug ARC the plain body with WALK stops memorising (.94 -> .26 on train demos) but learns no rule and finds no fixed
5
+ points (C-Q2-157); on Sudoku the judge and the self-training rest on an equivariant body (C-Q2-151/152/155). Colour 0 (background)
6
+ stays special -- ARC treats it so -- hence S9, not S10:
7
+ logits(pi . x, pi . e) = pi . logits(x, e) for pi fixing colour 0 (core/tests/smoke_a9.py (a); e = the task table)
8
+
9
+ Tokens: 900 cells x 10 colour slots = 9,000, COLOUR-MAJOR (hidden [B, 10*900, D] == [B, 10, 900, D]), no puzzle prefix. Slot k of
10
+ a cell is embedded from its type w.r.t. colour k (token 2 + k): {pad, EOS, colour == k, another colour}; slot 0 also gets a learned
11
+ background flag. The task embedding is the parent's sparse puzzle_emb (same SignSGD optimiser, lr and weight decay in pretrain.py)
12
+ at width 10 * D, read as one D-vector per colour slot and added to that slot of every cell at every input injection.
13
+ Block (post-norm, the S9Block frame): (i) per-slot attention over the 900 cells, one weight set for all slots, the parent's 1D RoPE
14
+ (the parent's self_attn: mlp_t=false); (ii) + (iii) = S9Block.mix_digits_channels: position-free attention over each cell's 10
15
+ slots, then the channel SwiGLU.
16
+ Output: per cell token 0 (pad) = -1e4, token 1 (EOS) = a linear read of the mean over the 10 slots, token 2 + k = slot k's scalar;
17
+ Q head on the mean over all 9,000 tokens.
18
+ Translation: forward moves each row's INPUT so its first row / column holding a token >= 1 lands on (0, 0) (a cyclic roll; the
19
+ rolled-in cells are pad) and rolls the logits back; the carry and z_H live in the aligned frame. The builder puts a pair's input
20
+ and label at the same offset (all 3,988 arc1concept-aug-0 train rows; 74% are offset), so label cells never wrap, the body is
21
+ exactly translation-invariant (smoke (c)) and the builder's random offsets carry no signal. Everything else (ACT wrapper,
22
+ carry, reset, H/L cycles, no-grad cycles, detach, walk) is the parent trm.py code.
23
+
24
+ arch.name=recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9 with arch.puzzle_emb_ndim = 10 * hidden_size,
25
+ arch.puzzle_emb_len=0, arch.pos_encodings=rope, arch.mlp_t=false.
26
+ """
27
+ import os
28
+ from typing import Dict
29
+
30
+ import torch
31
+
32
+ from models.layers import rms_norm, CastedEmbedding, CastedLinear, RotaryEmbedding
33
+ from models.recursive_reasoning.trm import (
34
+ TinyRecursiveReasoningModel_ACTV1Config, TinyRecursiveReasoningModel_ACTV1ReasoningModule,
35
+ TinyRecursiveReasoningModel_ACTV1_Inner, TinyRecursiveReasoningModel_ACTV1InnerCarry)
36
+ from models.recursive_reasoning.trm_s9 import S9Block, TinyRecursiveReasoningModel_S9
37
+
38
+ N_COL, SIDE = 10, 30 # colour slots (token 2 + k = colour k; 1 = EOS, 0 = pad); the canvas side
39
+
40
+
41
+ def shift(t: torch.Tensor, r: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
42
+ """t [B, 900, ...] -> t' with t'[b, (i, j)] = t[b, ((i + r_b) % 30, (j + c_b) % 30)] (a per-row cyclic roll by (-r_b, -c_b))."""
43
+ B, i = t.shape[0], torch.arange(SIDE, device=t.device)
44
+ rows, cols = ((i + r.view(B, 1)) % SIDE).view(B, SIDE, 1), ((i + c.view(B, 1)) % SIDE).view(B, 1, SIDE)
45
+ return t.view(B, SIDE, SIDE, *t.shape[2:])[torch.arange(B, device=t.device).view(B, 1, 1), rows, cols].view(t.shape)
46
+
47
+
48
+ class A9Block(S9Block):
49
+ """(i) cell attention per colour slot (shared weights, RoPE) -> S9Block's (ii) slot attention + (iii) channel MLP."""
50
+
51
+ def forward(self, cos_sin, hidden_states: torch.Tensor) -> torch.Tensor:
52
+ B, T, D = hidden_states.shape
53
+ h = hidden_states.view(B * N_COL, T // N_COL, D)
54
+ h = rms_norm(h + self.self_attn(cos_sin=cos_sin, hidden_states=h), variance_epsilon=self.norm_eps)
55
+ return self.mix_digits_channels(h.view(B, N_COL, T // N_COL, D))
56
+
57
+
58
+ class A9LMHead(torch.nn.Module):
59
+ """[B, 10*900, D] -> vocab logits [B, 900, 12]: pad -1e4, EOS from the slot mean, token 2 + k from slot k."""
60
+
61
+ def __init__(self, hidden_size: int) -> None:
62
+ super().__init__()
63
+ self.slot, self.eos = CastedLinear(hidden_size, 1, bias=False), CastedLinear(hidden_size, 1, bias=False)
64
+
65
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
66
+ z = z.view(z.shape[0], N_COL, -1, z.shape[-1])
67
+ col = self.slot(z)[..., 0].transpose(1, 2) # [B, 900, 10]
68
+ return torch.cat((col.new_full(col.shape[:2] + (1,), -1e4), self.eos(z.mean(1)), col), dim=-1)
69
+
70
+
71
+ class TinyRecursiveReasoningModel_A9_Inner(TinyRecursiveReasoningModel_ACTV1_Inner):
72
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
73
+ D = config.hidden_size
74
+ assert config.seq_len == SIDE * SIDE and config.vocab_size == N_COL + 2, "a9: ARC only (30 x 30, vocab 12)"
75
+ assert config.puzzle_emb_ndim == N_COL * D and config.puzzle_emb_len == 0 and config.puzzle_emb_mode == "lookup", \
76
+ "a9: puzzle_emb_ndim = 10 * hidden_size (one task vector per colour slot), puzzle_emb_len=0"
77
+ assert config.pos_encodings == "rope" and not config.mlp_t and config.fast_slice is None, "a9: rope, mlp_t=false, no fast slice"
78
+ assert not os.environ.get("SELF_COND"), "a9: SELF_COND is not supported"
79
+ super().__init__(config)
80
+ # the parent sized a ceil(ndim / D) = 10-slot prefix (the wrapper's z_H slice, the output slice, RoPE): a9 has none
81
+ self.puzzle_emb_len = 0
82
+ self.rotary_emb = RotaryEmbedding(dim=D // config.num_heads, max_position_embeddings=config.seq_len, base=config.rope_theta)
83
+ del self.embed_tokens
84
+ self.embed_types = CastedEmbedding(5, D, init_std=1.0 / self.embed_scale, cast_to=self.forward_dtype) # 4 types + bg flag
85
+ self.lm_head = A9LMHead(D)
86
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[A9Block(config) for _i in range(config.L_layers)])
87
+
88
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, prev_pred=None, ctx=None):
89
+ # slot k's type at a cell: 0 pad, 1 EOS, 2 colour == k, 3 another colour; row 4 of the table = slot 0's background flag
90
+ x, k = input.unsqueeze(1), torch.arange(2, 2 + N_COL, device=input.device).view(1, N_COL, 1)
91
+ types = torch.where(x < 2, x, torch.where(x == k, 2, 3)).to(torch.int32) # [B, 10, 900]
92
+ bg = (k == 2).unsqueeze(-1) * self.embed_types.embedding_weight[4].to(self.forward_dtype) # [1, 10, 1, D]
93
+ task = self.puzzle_emb(puzzle_identifiers).view(-1, N_COL, 1, self.config.hidden_size)
94
+ return self.embed_scale * (self.embed_types(types) + bg + task).flatten(1, 2)
95
+
96
+ def empty_carry(self, batch_size: int):
97
+ shape = (batch_size, N_COL * self.config.seq_len, self.config.hidden_size)
98
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=torch.empty(shape, dtype=self.forward_dtype),
99
+ z_L=torch.empty(shape, dtype=self.forward_dtype))
100
+
101
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]):
102
+ x = batch["inputs"]
103
+ g = (x >= 1).view(-1, SIDE, SIDE)
104
+ r0, c0 = g.any(2).int().argmax(1), g.any(1).int().argmax(1) # the anchor; (0, 0) for an all-pad row
105
+ new_carry, out, _, z_H = super().forward(carry, dict(batch, inputs=shift(x, r0, c0)))
106
+ q_logits = self.q_head(z_H.mean(dim=1)).to(torch.float32) # permutation-invariant Q (s9's)
107
+ return new_carry, shift(out, -r0, -c0), (q_logits[..., 0], q_logits[..., 1]), z_H
108
+
109
+
110
+ class TinyRecursiveReasoningModel_A9(TinyRecursiveReasoningModel_S9):
111
+ """ACT wrapper driving the a9 inner (§2cr)."""
112
+ inner_cls = TinyRecursiveReasoningModel_A9_Inner
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/all_config.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 128
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9
16
+ no_ACT_continue: true
17
+ num_heads: 4
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 0
20
+ puzzle_emb_ndim: 1280
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0
25
+ data_paths:
26
+ - data/arc_a9p1
27
+ data_paths_test: []
28
+ ema: false
29
+ ema_rate: 0.999
30
+ epochs: 1422
31
+ eval_interval: 1422
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 64
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 200
40
+ min_eval_interval: 0
41
+ project_name: Arc1concept-aug-0-ACT-torch
42
+ puzzle_emb_lr: 0.01
43
+ puzzle_emb_weight_decay: 0.1
44
+ run_name: trm_arc1_a9p1ne_s0
45
+ sam_rho: 0.0
46
+ seed: 0
47
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/losses.py ADDED
The diff for this file is too large to render. See raw diff
 
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/step_3000 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb7137a3d5421177ce0285bd2f068ab851ca995d71e6cbc482a71b2375329de8
3
+ size 7556443
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1ne_s0/trm_a9.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PREREG_Q2 §2cr a9: an ARC TRM body that is exactly equivariant to permutations of colours 1..9 (S9) and invariant to
2
+ where the grid sits on the 30 x 30 canvas.
3
+
4
+ Why: on no-aug ARC the plain body with WALK stops memorising (.94 -> .26 on train demos) but learns no rule and finds no fixed
5
+ points (C-Q2-157); on Sudoku the judge and the self-training rest on an equivariant body (C-Q2-151/152/155). Colour 0 (background)
6
+ stays special -- ARC treats it so -- hence S9, not S10:
7
+ logits(pi . x, pi . e) = pi . logits(x, e) for pi fixing colour 0 (core/tests/smoke_a9.py (a); e = the task table)
8
+
9
+ Tokens: 900 cells x 10 colour slots = 9,000, COLOUR-MAJOR (hidden [B, 10*900, D] == [B, 10, 900, D]), no puzzle prefix. Slot k of
10
+ a cell is embedded from its type w.r.t. colour k (token 2 + k): {pad, EOS, colour == k, another colour}; slot 0 also gets a learned
11
+ background flag. The task embedding is the parent's sparse puzzle_emb (same SignSGD optimiser, lr and weight decay in pretrain.py)
12
+ at width 10 * D, read as one D-vector per colour slot and added to that slot of every cell at every input injection.
13
+ Block (post-norm, the S9Block frame): (i) per-slot attention over the 900 cells, one weight set for all slots, the parent's 1D RoPE
14
+ (the parent's self_attn: mlp_t=false); (ii) + (iii) = S9Block.mix_digits_channels: position-free attention over each cell's 10
15
+ slots, then the channel SwiGLU.
16
+ Output: per cell token 0 (pad) = -1e4, token 1 (EOS) = a linear read of the mean over the 10 slots, token 2 + k = slot k's scalar;
17
+ Q head on the mean over all 9,000 tokens.
18
+ Translation: forward moves each row's INPUT so its first row / column holding a token >= 1 lands on (0, 0) (a cyclic roll; the
19
+ rolled-in cells are pad) and rolls the logits back; the carry and z_H live in the aligned frame. The builder puts a pair's input
20
+ and label at the same offset (all 3,988 arc1concept-aug-0 train rows; 74% are offset), so label cells never wrap, the body is
21
+ exactly translation-invariant (smoke (c)) and the builder's random offsets carry no signal. Everything else (ACT wrapper,
22
+ carry, reset, H/L cycles, no-grad cycles, detach, walk) is the parent trm.py code.
23
+
24
+ arch.name=recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9 with arch.puzzle_emb_ndim = 10 * hidden_size,
25
+ arch.puzzle_emb_len=0, arch.pos_encodings=rope, arch.mlp_t=false.
26
+ """
27
+ import os
28
+ from typing import Dict
29
+
30
+ import torch
31
+
32
+ from models.layers import rms_norm, CastedEmbedding, CastedLinear, RotaryEmbedding
33
+ from models.recursive_reasoning.trm import (
34
+ TinyRecursiveReasoningModel_ACTV1Config, TinyRecursiveReasoningModel_ACTV1ReasoningModule,
35
+ TinyRecursiveReasoningModel_ACTV1_Inner, TinyRecursiveReasoningModel_ACTV1InnerCarry)
36
+ from models.recursive_reasoning.trm_s9 import S9Block, TinyRecursiveReasoningModel_S9
37
+
38
+ N_COL, SIDE = 10, 30 # colour slots (token 2 + k = colour k; 1 = EOS, 0 = pad); the canvas side
39
+
40
+
41
+ def shift(t: torch.Tensor, r: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
42
+ """t [B, 900, ...] -> t' with t'[b, (i, j)] = t[b, ((i + r_b) % 30, (j + c_b) % 30)] (a per-row cyclic roll by (-r_b, -c_b))."""
43
+ B, i = t.shape[0], torch.arange(SIDE, device=t.device)
44
+ rows, cols = ((i + r.view(B, 1)) % SIDE).view(B, SIDE, 1), ((i + c.view(B, 1)) % SIDE).view(B, 1, SIDE)
45
+ return t.view(B, SIDE, SIDE, *t.shape[2:])[torch.arange(B, device=t.device).view(B, 1, 1), rows, cols].view(t.shape)
46
+
47
+
48
+ class A9Block(S9Block):
49
+ """(i) cell attention per colour slot (shared weights, RoPE) -> S9Block's (ii) slot attention + (iii) channel MLP."""
50
+
51
+ def forward(self, cos_sin, hidden_states: torch.Tensor) -> torch.Tensor:
52
+ B, T, D = hidden_states.shape
53
+ h = hidden_states.view(B * N_COL, T // N_COL, D)
54
+ h = rms_norm(h + self.self_attn(cos_sin=cos_sin, hidden_states=h), variance_epsilon=self.norm_eps)
55
+ return self.mix_digits_channels(h.view(B, N_COL, T // N_COL, D))
56
+
57
+
58
+ class A9LMHead(torch.nn.Module):
59
+ """[B, 10*900, D] -> vocab logits [B, 900, 12]: pad -1e4, EOS from the slot mean, token 2 + k from slot k."""
60
+
61
+ def __init__(self, hidden_size: int) -> None:
62
+ super().__init__()
63
+ self.slot, self.eos = CastedLinear(hidden_size, 1, bias=False), CastedLinear(hidden_size, 1, bias=False)
64
+
65
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
66
+ z = z.view(z.shape[0], N_COL, -1, z.shape[-1])
67
+ col = self.slot(z)[..., 0].transpose(1, 2) # [B, 900, 10]
68
+ return torch.cat((col.new_full(col.shape[:2] + (1,), -1e4), self.eos(z.mean(1)), col), dim=-1)
69
+
70
+
71
+ class TinyRecursiveReasoningModel_A9_Inner(TinyRecursiveReasoningModel_ACTV1_Inner):
72
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
73
+ D = config.hidden_size
74
+ assert config.seq_len == SIDE * SIDE and config.vocab_size == N_COL + 2, "a9: ARC only (30 x 30, vocab 12)"
75
+ assert config.puzzle_emb_ndim == N_COL * D and config.puzzle_emb_len == 0 and config.puzzle_emb_mode == "lookup", \
76
+ "a9: puzzle_emb_ndim = 10 * hidden_size (one task vector per colour slot), puzzle_emb_len=0"
77
+ assert config.pos_encodings == "rope" and not config.mlp_t and config.fast_slice is None, "a9: rope, mlp_t=false, no fast slice"
78
+ assert not os.environ.get("SELF_COND"), "a9: SELF_COND is not supported"
79
+ super().__init__(config)
80
+ # the parent sized a ceil(ndim / D) = 10-slot prefix (the wrapper's z_H slice, the output slice, RoPE): a9 has none
81
+ self.puzzle_emb_len = 0
82
+ self.rotary_emb = RotaryEmbedding(dim=D // config.num_heads, max_position_embeddings=config.seq_len, base=config.rope_theta)
83
+ del self.embed_tokens
84
+ self.embed_types = CastedEmbedding(5, D, init_std=1.0 / self.embed_scale, cast_to=self.forward_dtype) # 4 types + bg flag
85
+ self.lm_head = A9LMHead(D)
86
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[A9Block(config) for _i in range(config.L_layers)])
87
+
88
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, prev_pred=None, ctx=None):
89
+ # slot k's type at a cell: 0 pad, 1 EOS, 2 colour == k, 3 another colour; row 4 of the table = slot 0's background flag
90
+ x, k = input.unsqueeze(1), torch.arange(2, 2 + N_COL, device=input.device).view(1, N_COL, 1)
91
+ types = torch.where(x < 2, x, torch.where(x == k, 2, 3)).to(torch.int32) # [B, 10, 900]
92
+ bg = (k == 2).unsqueeze(-1) * self.embed_types.embedding_weight[4].to(self.forward_dtype) # [1, 10, 1, D]
93
+ task = self.puzzle_emb(puzzle_identifiers).view(-1, N_COL, 1, self.config.hidden_size)
94
+ return self.embed_scale * (self.embed_types(types) + bg + task).flatten(1, 2)
95
+
96
+ def empty_carry(self, batch_size: int):
97
+ shape = (batch_size, N_COL * self.config.seq_len, self.config.hidden_size)
98
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=torch.empty(shape, dtype=self.forward_dtype),
99
+ z_L=torch.empty(shape, dtype=self.forward_dtype))
100
+
101
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]):
102
+ x = batch["inputs"]
103
+ g = (x >= 1).view(-1, SIDE, SIDE)
104
+ r0, c0 = g.any(2).int().argmax(1), g.any(1).int().argmax(1) # the anchor; (0, 0) for an all-pad row
105
+ new_carry, out, _, z_H = super().forward(carry, dict(batch, inputs=shift(x, r0, c0)))
106
+ q_logits = self.q_head(z_H.mean(dim=1)).to(torch.float32) # permutation-invariant Q (s9's)
107
+ return new_carry, shift(out, -r0, -c0), (q_logits[..., 0], q_logits[..., 1]), z_H
108
+
109
+
110
+ class TinyRecursiveReasoningModel_A9(TinyRecursiveReasoningModel_S9):
111
+ """ACT wrapper driving the a9 inner (§2cr)."""
112
+ inner_cls = TinyRecursiveReasoningModel_A9_Inner
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/all_config.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 512
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm@TinyRecursiveReasoningModel_ACTV1
16
+ no_ACT_continue: true
17
+ num_heads: 8
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 16
20
+ puzzle_emb_ndim: 512
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0
25
+ data_paths:
26
+ - data/arc_a9p1
27
+ data_paths_test: []
28
+ ema: true
29
+ ema_rate: 0.999
30
+ epochs: 1422
31
+ eval_interval: 1422
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 64
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 200
40
+ min_eval_interval: 0
41
+ project_name: Arc1concept-aug-0-ACT-torch
42
+ puzzle_emb_lr: 0.01
43
+ puzzle_emb_weight_decay: 0.1
44
+ run_name: trm_arc1_a9p1plain_s0
45
+ sam_rho: 0.0
46
+ seed: 0
47
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/losses.py ADDED
The diff for this file is too large to render. See raw diff
 
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/step_3000 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e93a29d14e88aac126d498766a2d63753bc1e173405bf3bc7fdb4e597c19ac4c
3
+ size 29293856
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plain_s0/trm.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List, Dict, Optional
2
+ from dataclasses import dataclass
3
+ import math
4
+ import os
5
+ import numpy as np
6
+ import torch
7
+ import copy
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+ from pydantic import BaseModel
11
+ import random
12
+ from models.common import trunc_normal_init_
13
+ from models.layers import rms_norm, LinearSwish, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear, set_fast_lora
14
+ from models.sparse_embedding import CastedSparseEmbedding
15
+
16
+ IGNORE_LABEL_ID = -100
17
+
18
+ @dataclass
19
+ class TinyRecursiveReasoningModel_ACTV1InnerCarry:
20
+ z_H: torch.Tensor
21
+ z_L: torch.Tensor
22
+ # FAST SLICE: optional per-sample fast weights phi. None (default) => every code path below
23
+ # is bit-for-bit the original TRM. Keys: "ctx" [B, puzzle_emb_len, hidden] replacing the
24
+ # puzzle-embedding prefix, "lora" {key: (A [B,in,r], B [B,r,out])} for the L_level channel MLPs.
25
+ phi: Optional[Dict[str, object]] = None
26
+
27
+
28
+ @dataclass
29
+ class TinyRecursiveReasoningModel_ACTV1Carry:
30
+ inner_carry: TinyRecursiveReasoningModel_ACTV1InnerCarry
31
+
32
+ steps: torch.Tensor
33
+ halted: torch.Tensor
34
+
35
+ current_data: Dict[str, torch.Tensor]
36
+
37
+
38
+ class TinyRecursiveReasoningModel_ACTV1Config(BaseModel):
39
+ batch_size: int
40
+ seq_len: int
41
+ puzzle_emb_ndim: int = 0
42
+ num_puzzle_identifiers: int
43
+ vocab_size: int
44
+
45
+ H_cycles: int
46
+ L_cycles: int
47
+
48
+ H_layers: int # ignored
49
+ L_layers: int
50
+
51
+ # Transformer config
52
+ hidden_size: int
53
+ expansion: float
54
+ num_heads: int
55
+ pos_encodings: str
56
+
57
+ rms_norm_eps: float = 1e-5
58
+ rope_theta: float = 10000.0
59
+
60
+ # Halting Q-learning config
61
+ halt_max_steps: int
62
+ halt_exploration_prob: float
63
+ # PREREG_Q2 §2cd. False = "walk": in TRAINING a row halts only at halt_max_steps (no q-halt, no exploration; the q
64
+ # losses / targets are still computed) and initial_carry staggers the rows' first episode. Default True => the
65
+ # original halting and RNG stream, bit for bit. Eval is the same for both values.
66
+ act_halt: bool = True
67
+ # PREREG_Q2 §2ck K1 (EqR random init + path noise, Anil mixed init). TRAINING only, eval never draws:
68
+ # train_init_noise: a row (re)initialised by reset_carry whose batch index is ODD starts from z_H, z_L = train_init_noise * N(0,1)
69
+ # (the H_init / L_init buffers are trunc-normal std 1, so 1.0 = the same scale) instead of H_init / L_init; even rows keep the
70
+ # standard (eval) init.
71
+ # train_step_noise (beta): after every segment the CARRIED z_H of every row gets + beta * rms(z_H of that row) * N(0,1); the
72
+ # segment's outputs (logits, z_H, q) are the clean ones and the noise carries no gradient.
73
+ # 0.0 (default) => nothing is drawn: bit-identical, RNG stream included.
74
+ train_init_noise: float = 0.0
75
+ train_step_noise: float = 0.0
76
+
77
+ forward_dtype: str = "bfloat16"
78
+
79
+ # Alexia: added
80
+ mlp_t: bool = False # use mlp on L instead of transformer
81
+ puzzle_emb_len: int = 16 # if non-zero, its specified to this value
82
+ no_ACT_continue: bool = True # No continue ACT loss, only use the sigmoid of the halt which makes much more sense
83
+
84
+ # Task representation. "lookup": the original per-task learned prefix (a row of a sparse
85
+ # embedding table, indexed by puzzle_identifier). "demo": the prefix is COMPUTED from the
86
+ # task's demonstration pairs by a small cross-attention encoder, so it is a function of the
87
+ # demos rather than a memorised row. Motivation: with "lookup" and no augmentation the
88
+ # model solves 81% of ARC train pairs but only 3.1% of a held-out demo of the SAME task
89
+ # (leave-one-demo-out) -- the table can memorise grids but has no path from demos to rule.
90
+ puzzle_emb_mode: str = "lookup"
91
+ demo_bank_path: str = "" # npz with demo_in/demo_out [P,K,seq_len] uint8, demo_valid [P,K]
92
+
93
+ # Fast slice: a small PER-SAMPLE parameter set carried in the carry, so a test-time
94
+ # adaptation loop can adapt one puzzle without touching the shared weights W.
95
+ # None = off (identical to the original model). "ctx" = per-sample puzzle prefix,
96
+ # "lora" = per-sample rank-r deltas on the L_level channel MLPs.
97
+ fast_slice: Optional[str] = None
98
+ fast_lora_rank: int = 8
99
+ # PREREG_Q2 §2as. With "lora", init_phi draws the A factor i.i.d. PER ROW, so two rows of
100
+ # the SAME task live in different random bases and a demo row's gradient on B is
101
+ # meaningless for the query row's B. Episodic meta-training (ArcMetaLossHead) needs one
102
+ # shared basis, so this flag replaces the per-row draw with ONE fixed A (a buffer, drawn
103
+ # once from a private generator so the global RNG stream is untouched) shared by every row
104
+ # and every task; only B (init exactly 0) is then per-row/per-task state.
105
+ # Default False => init_phi is bit-for-bit the old path (Q3 sudoku runs are unaffected).
106
+ fast_lora_shared_A: bool = False
107
+ # PREREG_Q2 §2as. reset_carry re-inits a halted row's phi with torch.where(flag, init, phi),
108
+ # which also CUTS the gradient path to phi on exactly the rows that were just reset -- so an
109
+ # inner loop that differentiates the segment w.r.t. phi gets an all-zero gradient on them.
110
+ # With this flag the model leaves phi alone and the LOSS HEAD owns the reset (it zeroes the
111
+ # halted rows' B itself, before the forward, on tensors it made leaves). Default False =>
112
+ # reset_carry is bit-for-bit the old path.
113
+ fast_slice_external_reset: bool = False
114
+
115
+ class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
116
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
117
+ super().__init__()
118
+
119
+ self.config = config
120
+ if self.config.mlp_t:
121
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len
122
+ self.mlp_t = SwiGLU(
123
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
124
+ expansion=config.expansion,
125
+ )
126
+ else:
127
+ self.self_attn = Attention(
128
+ hidden_size=config.hidden_size,
129
+ head_dim=config.hidden_size // config.num_heads,
130
+ num_heads=config.num_heads,
131
+ num_key_value_heads=config.num_heads,
132
+ causal=False
133
+ )
134
+ self.mlp = SwiGLU(
135
+ hidden_size=config.hidden_size,
136
+ expansion=config.expansion,
137
+ )
138
+ self.norm_eps = config.rms_norm_eps
139
+
140
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
141
+ # B, L, D = hidden_states.shape
142
+ # Post Norm
143
+ if self.config.mlp_t:
144
+ hidden_states = hidden_states.transpose(1,2)
145
+ out = self.mlp_t(hidden_states)
146
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
147
+ hidden_states = hidden_states.transpose(1,2)
148
+ else:
149
+ # Self Attention
150
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
151
+ # Fully Connected
152
+ out = self.mlp(hidden_states)
153
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
154
+ return hidden_states
155
+
156
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
157
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
158
+ super().__init__()
159
+ self.layers = torch.nn.ModuleList(layers)
160
+
161
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
162
+ hidden_states = hidden_states + input_injection
163
+ for layer in self.layers:
164
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
165
+ return hidden_states
166
+
167
+
168
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
169
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
170
+ super().__init__()
171
+ self.config = config
172
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
173
+
174
+ # I/O
175
+
176
+ self.embed_scale = math.sqrt(self.config.hidden_size)
177
+ embed_init_std = 1.0 / self.embed_scale
178
+
179
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
180
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
181
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
182
+
183
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len # ceil div
184
+ if self.config.puzzle_emb_mode == "demo":
185
+ bank = np.load(self.config.demo_bank_path)
186
+ self.register_buffer("demo_in", torch.tensor(bank["demo_in"], dtype=torch.int32), persistent=False)
187
+ self.register_buffer("demo_out", torch.tensor(bank["demo_out"], dtype=torch.int32), persistent=False)
188
+ self.register_buffer("demo_valid", torch.tensor(bank["demo_valid"], dtype=torch.bool), persistent=False)
189
+ H = self.config.hidden_size
190
+ self.demo_type = nn.Parameter(trunc_normal_init_(torch.empty(2, H), std=embed_init_std))
191
+ self.demo_pos = nn.Parameter(trunc_normal_init_(torch.empty(self.config.seq_len, H), std=embed_init_std))
192
+ self.demo_queries = nn.Parameter(trunc_normal_init_(torch.empty(self.puzzle_emb_len, H), std=embed_init_std))
193
+ # cross-attention written out so the weights can be cast to forward_dtype at use
194
+ # (nn.MultiheadAttention keeps fp32 params and rejects bf16 inputs)
195
+ self.demo_q = CastedLinear(H, H, bias=False)
196
+ self.demo_kv = CastedLinear(H, 2 * H, bias=False)
197
+ self.demo_o = CastedLinear(H, H, bias=False)
198
+ self.demo_norm = nn.LayerNorm(H)
199
+ self.demo_mlp = nn.Sequential(nn.Linear(H, 4 * H), nn.GELU(), nn.Linear(4 * H, H))
200
+ if self.config.puzzle_emb_ndim > 0 and self.config.puzzle_emb_mode == "lookup":
201
+ # Zero init puzzle embeddings
202
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
203
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
204
+
205
+ # LM Blocks
206
+ if self.config.pos_encodings == "rope":
207
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
208
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
209
+ base=self.config.rope_theta)
210
+ elif self.config.pos_encodings == "learned":
211
+ self.embed_pos = CastedEmbedding(self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
212
+ else:
213
+ pass
214
+
215
+ # Reasoning Layers
216
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
217
+
218
+ # Initial states
219
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
220
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
221
+
222
+ # Fixed shared LoRA basis (see config.fast_lora_shared_A). Drawn from a PRIVATE
223
+ # generator: torch.randn(generator=g) does not advance the global RNG, so turning the
224
+ # flag on cannot shift halt_exploration's rand_like stream.
225
+ if self.config.fast_slice == "lora" and self.config.fast_lora_shared_A:
226
+ g = torch.Generator(device="cpu").manual_seed(0)
227
+ r = self.config.fast_lora_rank
228
+ for key, mod in self._fast_lora_targets():
229
+ in_f = mod.weight.shape[1]
230
+ self.register_buffer(
231
+ "fastA_" + key.replace(".", "__"),
232
+ torch.randn(in_f, r, generator=g, device="cpu") * (in_f ** -0.5),
233
+ persistent=True)
234
+
235
+ # Q head special init
236
+ # Init Q to (almost) zero for faster learning during bootstrapping
237
+ with torch.no_grad():
238
+ self.q_head.weight.zero_()
239
+ self.q_head.bias.fill_(-5) # type: ignore
240
+
241
+ def _demo_prefix(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
242
+ """[B, puzzle_emb_len, H] task prefix computed from the task's demonstration pairs.
243
+
244
+ A demo whose input grid equals THIS example's input is masked out, so a training row
245
+ that is itself one of the task's demos is encoded from the OTHER demos only -- the
246
+ model is trained to predict a demo it cannot see (leave-one-demo-out), which is the
247
+ within-task generalisation the lookup table never had to learn. No grid is ever
248
+ transformed or duplicated, so this is not augmentation.
249
+ """
250
+ din, dout, valid = self.demo_in[puzzle_identifiers], self.demo_out[puzzle_identifiers], self.demo_valid[puzzle_identifiers]
251
+ B, K, S = din.shape
252
+ valid = valid & ~(din == input.to(din.dtype).unsqueeze(1)).all(-1)
253
+ no_demo = ~valid.any(-1)
254
+ pos = self.demo_pos.to(self.forward_dtype)
255
+ e_in = self.embed_tokens(din) + pos + self.demo_type[0].to(self.forward_dtype)
256
+ e_out = self.embed_tokens(dout) + pos + self.demo_type[1].to(self.forward_dtype)
257
+ kv = torch.cat((e_in, e_out), 2).reshape(B, K * 2 * S, -1) # [B, K*2S, H]
258
+ pad = torch.cat((din == 0, dout == 0), 2).reshape(B, K * 2 * S) # pad tokens carry nothing
259
+ keymask = pad | ~valid.repeat_interleave(2 * S, dim=1)
260
+ keymask = keymask & ~keymask.all(-1, keepdim=True) # never mask an entire row (NaN guard)
261
+ nh, hd = self.config.num_heads, self.config.hidden_size // self.config.num_heads
262
+ q = self.demo_queries.to(self.forward_dtype).unsqueeze(0).expand(B, -1, -1)
263
+ Q = self.demo_q(q).view(B, -1, nh, hd).transpose(1, 2) # [B,nh,16,hd]
264
+ Kv = self.demo_kv(kv).view(B, kv.shape[1], 2, nh, hd)
265
+ Kx, Vx = Kv[:, :, 0].transpose(1, 2), Kv[:, :, 1].transpose(1, 2) # [B,nh,N,hd]
266
+ out = F.scaled_dot_product_attention(Q, Kx, Vx, attn_mask=(~keymask)[:, None, None, :]) # True = attend
267
+ out = self.demo_o(out.transpose(1, 2).reshape(B, -1, self.config.hidden_size))
268
+ out = out + self.demo_mlp(self.demo_norm(out.float())).to(out.dtype)
269
+ return out * self.embed_scale, no_demo
270
+
271
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor,
272
+ prev_pred: Optional[torch.Tensor] = None, ctx: Optional[torch.Tensor] = None):
273
+ # Token embedding
274
+ embedding = self.embed_tokens(input.to(torch.int32))
275
+
276
+ # SELF_COND (PREREG_Q2 §2q): input-side self-conditioning. The previous segment's
277
+ # argmax prediction (carried row-aligned in current_data["prev_pred"], detached) is
278
+ # embedded with the SAME token table and ADDED to the input embedding, before the
279
+ # puzzle prefix is concatenated. No new parameter is introduced, so every existing
280
+ # checkpoint still loads. Token 0 == pad == "no prediction", which is what a freshly
281
+ # reset row carries (the ACT wrapper's torch.where over current_data restores
282
+ # batch["prev_pred"], which the loss head fills with zeros). prev_pred is None unless
283
+ # the loss head put the key in the batch AND SELF_COND is set, so with SELF_COND
284
+ # unset this path is bit-for-bit the original.
285
+ if prev_pred is not None:
286
+ embedding = embedding + self.embed_tokens(prev_pred.to(torch.int32))
287
+
288
+ # Puzzle embeddings
289
+ if self.config.puzzle_emb_mode == "demo":
290
+ prefix, _ = self._demo_prefix(input, puzzle_identifiers)
291
+ embedding = torch.cat((prefix.to(embedding.dtype), embedding), dim=-2)
292
+ elif self.config.puzzle_emb_ndim > 0:
293
+ if ctx is not None:
294
+ # FAST SLICE "ctx": the per-sample slice replaces the lookup output entirely.
295
+ prefix = ctx.to(embedding.dtype)
296
+ else:
297
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
298
+
299
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
300
+ if pad_count > 0:
301
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
302
+ prefix = puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size)
303
+
304
+ embedding = torch.cat((prefix, embedding), dim=-2)
305
+
306
+ # Position embeddings
307
+ if self.config.pos_encodings == "learned":
308
+ # scale by 1/sqrt(2) to maintain forward variance
309
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
310
+
311
+ # Scale
312
+ return self.embed_scale * embedding
313
+
314
+ def empty_carry(self, batch_size: int):
315
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
316
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
317
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
318
+ )
319
+
320
+ def _fast_lora_targets(self):
321
+ """Ordered (key, module) of the channel-MLP projections a "lora" fast slice adapts."""
322
+ return [(f"{i}.{name}", getattr(layer.mlp, name))
323
+ for i, layer in enumerate(self.L_level.layers)
324
+ for name in ("gate_up_proj", "down_proj")]
325
+
326
+ @torch.no_grad()
327
+ def init_phi(self, batch_size: int, device):
328
+ """Fresh per-sample fast slice, initialised so the model is identical to the base model.
329
+
330
+ "ctx": per-sample copy of the puzzle-embedding lookup row 0 (padded/reshaped exactly as
331
+ the lookup output is). "lora": A ~ N(0, 1/in), B = 0, so the delta is zero.
332
+ """
333
+ mode = self.config.fast_slice
334
+ if mode == "ctx":
335
+ assert hasattr(self, "puzzle_emb"), "fast_slice=ctx needs puzzle_emb_ndim>0 and puzzle_emb_mode=lookup"
336
+ w = self.puzzle_emb.weights[0]
337
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - w.shape[-1]
338
+ if pad_count > 0:
339
+ w = F.pad(w, (0, pad_count))
340
+ ctx = w.view(1, self.puzzle_emb_len, self.config.hidden_size).to(device=device, dtype=self.forward_dtype)
341
+ return {"ctx": ctx.expand(batch_size, -1, -1).contiguous()}
342
+ if mode == "lora":
343
+ r = self.config.fast_lora_rank
344
+ lora = {}
345
+ shared = self.config.fast_lora_shared_A
346
+ for key, mod in self._fast_lora_targets():
347
+ out_f, in_f = mod.weight.shape
348
+ if shared:
349
+ a = getattr(self, "fastA_" + key.replace(".", "__")).to(
350
+ device=device, dtype=self.forward_dtype).unsqueeze(0).expand(batch_size, -1, -1).contiguous()
351
+ else:
352
+ a = torch.randn(batch_size, in_f, r, device=device, dtype=self.forward_dtype) * (in_f ** -0.5)
353
+ lora[key] = (a, torch.zeros(batch_size, r, out_f, device=device, dtype=self.forward_dtype))
354
+ return {"lora": lora}
355
+ raise ValueError(f"unknown fast_slice {mode!r}")
356
+
357
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
358
+ H_init, L_init = self.H_init, self.L_init
359
+ hinit_noise = os.environ.get("HINIT_NOISE")
360
+ if hinit_noise and self.training:
361
+ sigma = float(hinit_noise)
362
+ H_init = H_init + sigma * H_init.std() * torch.randn_like(carry.z_H)
363
+ L_init = L_init + sigma * L_init.std() * torch.randn_like(carry.z_L)
364
+ phi = carry.phi
365
+ if phi is not None and not self.config.fast_slice_external_reset and bool(reset_flag.any()):
366
+ # a halted row's fast slice goes back to its init, exactly like z_H/z_L
367
+ init = self.init_phi(carry.z_H.shape[0], carry.z_H.device)
368
+ flag = reset_flag.view(-1, 1, 1)
369
+ if "ctx" in phi:
370
+ phi = {"ctx": torch.where(flag, init["ctx"], phi["ctx"])}
371
+ else:
372
+ phi = {"lora": {k: (torch.where(flag, init["lora"][k][0], a), torch.where(flag, init["lora"][k][1], b))
373
+ for k, (a, b) in phi["lora"].items()}}
374
+ z_H = torch.where(reset_flag.view(-1, 1, 1), H_init, carry.z_H)
375
+ z_L = torch.where(reset_flag.view(-1, 1, 1), L_init, carry.z_L)
376
+ if self.training and self.config.train_init_noise > 0: # §2ck K1: the odd rows being reset start at random
377
+ odd = (reset_flag & (torch.arange(reset_flag.shape[0], device=reset_flag.device) % 2 == 1)).view(-1, 1, 1)
378
+ z_H = torch.where(odd, self.config.train_init_noise * torch.randn_like(z_H), z_H)
379
+ z_L = torch.where(odd, self.config.train_init_noise * torch.randn_like(z_L), z_L)
380
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H, z_L=z_L, phi=phi)
381
+
382
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
383
+ seq_info = dict(
384
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
385
+ )
386
+
387
+ # Input encoding
388
+ prev_pred = batch.get("prev_pred") if os.environ.get("SELF_COND") else None
389
+ phi = carry.phi or {}
390
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], prev_pred, ctx=phi.get("ctx"))
391
+
392
+ # Forward iterations
393
+ it = 0
394
+ z_H, z_L = carry.z_H, carry.z_L
395
+ lora = phi.get("lora")
396
+ lora_ctx = {id(mod): lora[key] for key, mod in self._fast_lora_targets()} if lora is not None else None
397
+ try:
398
+ if lora_ctx is not None:
399
+ set_fast_lora(lora_ctx)
400
+ # H_cycles-1 without grad
401
+ with torch.no_grad():
402
+ for _H_step in range(self.config.H_cycles-1):
403
+ for _L_step in range(self.config.L_cycles):
404
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
405
+ z_H = self.L_level(z_H, z_L, **seq_info)
406
+ # 1 with grad
407
+ for _L_step in range(self.config.L_cycles):
408
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
409
+ z_H = self.L_level(z_H, z_L, **seq_info)
410
+ finally:
411
+ if lora_ctx is not None:
412
+ set_fast_lora(None)
413
+
414
+ # LM Outputs
415
+ # Default: detach the carry every segment (original TRM/HRM "1-step gradient"
416
+ # design -- memory-cheap, but a later segment's loss can never influence an
417
+ # earlier segment's parameter update). KEEP_GRAD_CARRY=1 skips the detach so an
418
+ # external training loop can connect gradient across a window of consecutive
419
+ # segments before detaching itself; unset, behavior is bit-for-bit identical to
420
+ # every existing checkpoint in this repo.
421
+ if os.environ.get("KEEP_GRAD_CARRY"):
422
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H, z_L=z_L, phi=carry.phi)
423
+ else:
424
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach(), phi=carry.phi) # New carry no grad
425
+ if self.training and self.config.train_step_noise > 0: # §2ck K1: path noise on the carried z_H only (outputs stay clean)
426
+ c = new_carry.z_H
427
+ rms = c.detach().float().square().mean(dim=(1, 2), keepdim=True).sqrt()
428
+ new_carry.z_H = (c + self.config.train_step_noise * rms * torch.randn_like(c, dtype=torch.float32)).to(c.dtype)
429
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
430
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
431
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1]), z_H # z_H: solved-state target (losses.SolvedTargetLossHead)
432
+
433
+
434
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
435
+ """ACT wrapper."""
436
+
437
+ def __init__(self, config_dict: dict):
438
+ super().__init__()
439
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
440
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
441
+
442
+ @property
443
+ def puzzle_emb(self):
444
+ return self.inner.puzzle_emb
445
+
446
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
447
+ batch_size = batch["inputs"].shape[0]
448
+
449
+ inner_carry = self.inner.empty_carry(batch_size)
450
+ if self.config.fast_slice in ("ctx", "lora"):
451
+ # phi is data, not a parameter: an adaptation loop sets requires_grad on it itself.
452
+ inner_carry.phi = self.inner.init_phi(batch_size, inner_carry.z_H.device)
453
+
454
+ steps = torch.zeros((batch_size, ), dtype=torch.int32)
455
+ if self.training and not self.config.act_halt:
456
+ # Walk mode: every episode lasts exactly H = halt_max_steps segments, so rows that start together stay in
457
+ # lockstep and every batch would sit at ONE segment for the whole run. Only the FIRST episode is staggered:
458
+ # steps = -o (o = H-1 - i mod H), which forward's reset turns into a start at segment o+1, so row i's first
459
+ # episode lasts (i mod H)+1 segments, every later one H, and each batch holds every segment equally often.
460
+ # (That first episode starts from the fresh carry at segment index o+1: a one-episode transient.)
461
+ H = self.config.halt_max_steps
462
+ steps = torch.arange(batch_size, dtype=torch.int32) % H - (H - 1)
463
+
464
+ return TinyRecursiveReasoningModel_ACTV1Carry(
465
+ inner_carry=inner_carry, # Empty is expected, it will be reseted in first pass as all sequences are halted.
466
+
467
+ steps=steps,
468
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
469
+
470
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
471
+ )
472
+
473
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
474
+
475
+ # Update data, carry (removing halted sequences)
476
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
477
+
478
+ new_steps = torch.where(carry.halted, (-carry.steps).clamp_min(0), carry.steps) # 0, or initial_carry's stagger o
479
+
480
+ new_current_data = {k: torch.where(carry.halted.view((-1, ) + (1, ) * (batch[k].ndim - 1)), batch[k], v) for k, v in carry.current_data.items()}
481
+
482
+ # Forward inner model
483
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits), z_H = self.inner(new_inner_carry, new_current_data)
484
+
485
+ outputs = {
486
+ "logits": logits,
487
+ "z_H": z_H[:, self.inner.puzzle_emb_len:],
488
+ "q_halt_logits": q_halt_logits,
489
+ "q_continue_logits": q_continue_logits
490
+ }
491
+
492
+ with torch.no_grad():
493
+ # Step
494
+ new_steps = new_steps + 1
495
+ is_last_step = new_steps >= self.config.halt_max_steps
496
+
497
+ halted = is_last_step
498
+
499
+ # if training, and ACT is enabled
500
+ if self.training and (self.config.halt_max_steps > 1):
501
+
502
+ if self.config.act_halt: # (else: the walk, halted stays is_last_step)
503
+ # Halt signal
504
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
505
+
506
+ if self.config.no_ACT_continue:
507
+ halted = halted | (q_halt_logits > 0)
508
+ else:
509
+ halted = halted | (q_halt_logits > q_continue_logits)
510
+
511
+ # Exploration
512
+ min_halt_steps = (torch.rand_like(q_halt_logits) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
513
+ halted = halted & (new_steps >= min_halt_steps)
514
+
515
+ if not self.config.no_ACT_continue:
516
+ # Compute target Q
517
+ # NOTE: No replay buffer and target networks for computing target Q-value.
518
+ # As batch_size is large, there're many parallel envs.
519
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
520
+ _, _, (next_q_halt_logits, next_q_continue_logits), _ = self.inner(new_inner_carry, new_current_data)
521
+ outputs["target_q_continue"] = torch.sigmoid(torch.where(is_last_step, next_q_halt_logits, torch.maximum(next_q_halt_logits, next_q_continue_logits)))
522
+
523
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/all_config.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 512
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm@TinyRecursiveReasoningModel_ACTV1
16
+ no_ACT_continue: true
17
+ num_heads: 8
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 16
20
+ puzzle_emb_ndim: 512
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0
25
+ data_paths:
26
+ - data/arc_a9p1
27
+ data_paths_test: []
28
+ ema: false
29
+ ema_rate: 0.999
30
+ epochs: 1422
31
+ eval_interval: 1422
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 64
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 200
40
+ min_eval_interval: 0
41
+ project_name: Arc1concept-aug-0-ACT-torch
42
+ puzzle_emb_lr: 0.01
43
+ puzzle_emb_weight_decay: 0.1
44
+ run_name: trm_arc1_a9p1plainne_s0
45
+ sam_rho: 0.0
46
+ seed: 0
47
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/losses.py ADDED
The diff for this file is too large to render. See raw diff
 
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/step_3000 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:807c3b342277d837ed5522f5b5be24b51c282ed03e932d98a642574ddcd2dce0
3
+ size 29293856
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1plainne_s0/trm.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List, Dict, Optional
2
+ from dataclasses import dataclass
3
+ import math
4
+ import os
5
+ import numpy as np
6
+ import torch
7
+ import copy
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+ from pydantic import BaseModel
11
+ import random
12
+ from models.common import trunc_normal_init_
13
+ from models.layers import rms_norm, LinearSwish, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear, set_fast_lora
14
+ from models.sparse_embedding import CastedSparseEmbedding
15
+
16
+ IGNORE_LABEL_ID = -100
17
+
18
+ @dataclass
19
+ class TinyRecursiveReasoningModel_ACTV1InnerCarry:
20
+ z_H: torch.Tensor
21
+ z_L: torch.Tensor
22
+ # FAST SLICE: optional per-sample fast weights phi. None (default) => every code path below
23
+ # is bit-for-bit the original TRM. Keys: "ctx" [B, puzzle_emb_len, hidden] replacing the
24
+ # puzzle-embedding prefix, "lora" {key: (A [B,in,r], B [B,r,out])} for the L_level channel MLPs.
25
+ phi: Optional[Dict[str, object]] = None
26
+
27
+
28
+ @dataclass
29
+ class TinyRecursiveReasoningModel_ACTV1Carry:
30
+ inner_carry: TinyRecursiveReasoningModel_ACTV1InnerCarry
31
+
32
+ steps: torch.Tensor
33
+ halted: torch.Tensor
34
+
35
+ current_data: Dict[str, torch.Tensor]
36
+
37
+
38
+ class TinyRecursiveReasoningModel_ACTV1Config(BaseModel):
39
+ batch_size: int
40
+ seq_len: int
41
+ puzzle_emb_ndim: int = 0
42
+ num_puzzle_identifiers: int
43
+ vocab_size: int
44
+
45
+ H_cycles: int
46
+ L_cycles: int
47
+
48
+ H_layers: int # ignored
49
+ L_layers: int
50
+
51
+ # Transformer config
52
+ hidden_size: int
53
+ expansion: float
54
+ num_heads: int
55
+ pos_encodings: str
56
+
57
+ rms_norm_eps: float = 1e-5
58
+ rope_theta: float = 10000.0
59
+
60
+ # Halting Q-learning config
61
+ halt_max_steps: int
62
+ halt_exploration_prob: float
63
+ # PREREG_Q2 §2cd. False = "walk": in TRAINING a row halts only at halt_max_steps (no q-halt, no exploration; the q
64
+ # losses / targets are still computed) and initial_carry staggers the rows' first episode. Default True => the
65
+ # original halting and RNG stream, bit for bit. Eval is the same for both values.
66
+ act_halt: bool = True
67
+ # PREREG_Q2 §2ck K1 (EqR random init + path noise, Anil mixed init). TRAINING only, eval never draws:
68
+ # train_init_noise: a row (re)initialised by reset_carry whose batch index is ODD starts from z_H, z_L = train_init_noise * N(0,1)
69
+ # (the H_init / L_init buffers are trunc-normal std 1, so 1.0 = the same scale) instead of H_init / L_init; even rows keep the
70
+ # standard (eval) init.
71
+ # train_step_noise (beta): after every segment the CARRIED z_H of every row gets + beta * rms(z_H of that row) * N(0,1); the
72
+ # segment's outputs (logits, z_H, q) are the clean ones and the noise carries no gradient.
73
+ # 0.0 (default) => nothing is drawn: bit-identical, RNG stream included.
74
+ train_init_noise: float = 0.0
75
+ train_step_noise: float = 0.0
76
+
77
+ forward_dtype: str = "bfloat16"
78
+
79
+ # Alexia: added
80
+ mlp_t: bool = False # use mlp on L instead of transformer
81
+ puzzle_emb_len: int = 16 # if non-zero, its specified to this value
82
+ no_ACT_continue: bool = True # No continue ACT loss, only use the sigmoid of the halt which makes much more sense
83
+
84
+ # Task representation. "lookup": the original per-task learned prefix (a row of a sparse
85
+ # embedding table, indexed by puzzle_identifier). "demo": the prefix is COMPUTED from the
86
+ # task's demonstration pairs by a small cross-attention encoder, so it is a function of the
87
+ # demos rather than a memorised row. Motivation: with "lookup" and no augmentation the
88
+ # model solves 81% of ARC train pairs but only 3.1% of a held-out demo of the SAME task
89
+ # (leave-one-demo-out) -- the table can memorise grids but has no path from demos to rule.
90
+ puzzle_emb_mode: str = "lookup"
91
+ demo_bank_path: str = "" # npz with demo_in/demo_out [P,K,seq_len] uint8, demo_valid [P,K]
92
+
93
+ # Fast slice: a small PER-SAMPLE parameter set carried in the carry, so a test-time
94
+ # adaptation loop can adapt one puzzle without touching the shared weights W.
95
+ # None = off (identical to the original model). "ctx" = per-sample puzzle prefix,
96
+ # "lora" = per-sample rank-r deltas on the L_level channel MLPs.
97
+ fast_slice: Optional[str] = None
98
+ fast_lora_rank: int = 8
99
+ # PREREG_Q2 §2as. With "lora", init_phi draws the A factor i.i.d. PER ROW, so two rows of
100
+ # the SAME task live in different random bases and a demo row's gradient on B is
101
+ # meaningless for the query row's B. Episodic meta-training (ArcMetaLossHead) needs one
102
+ # shared basis, so this flag replaces the per-row draw with ONE fixed A (a buffer, drawn
103
+ # once from a private generator so the global RNG stream is untouched) shared by every row
104
+ # and every task; only B (init exactly 0) is then per-row/per-task state.
105
+ # Default False => init_phi is bit-for-bit the old path (Q3 sudoku runs are unaffected).
106
+ fast_lora_shared_A: bool = False
107
+ # PREREG_Q2 §2as. reset_carry re-inits a halted row's phi with torch.where(flag, init, phi),
108
+ # which also CUTS the gradient path to phi on exactly the rows that were just reset -- so an
109
+ # inner loop that differentiates the segment w.r.t. phi gets an all-zero gradient on them.
110
+ # With this flag the model leaves phi alone and the LOSS HEAD owns the reset (it zeroes the
111
+ # halted rows' B itself, before the forward, on tensors it made leaves). Default False =>
112
+ # reset_carry is bit-for-bit the old path.
113
+ fast_slice_external_reset: bool = False
114
+
115
+ class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
116
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
117
+ super().__init__()
118
+
119
+ self.config = config
120
+ if self.config.mlp_t:
121
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len
122
+ self.mlp_t = SwiGLU(
123
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
124
+ expansion=config.expansion,
125
+ )
126
+ else:
127
+ self.self_attn = Attention(
128
+ hidden_size=config.hidden_size,
129
+ head_dim=config.hidden_size // config.num_heads,
130
+ num_heads=config.num_heads,
131
+ num_key_value_heads=config.num_heads,
132
+ causal=False
133
+ )
134
+ self.mlp = SwiGLU(
135
+ hidden_size=config.hidden_size,
136
+ expansion=config.expansion,
137
+ )
138
+ self.norm_eps = config.rms_norm_eps
139
+
140
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
141
+ # B, L, D = hidden_states.shape
142
+ # Post Norm
143
+ if self.config.mlp_t:
144
+ hidden_states = hidden_states.transpose(1,2)
145
+ out = self.mlp_t(hidden_states)
146
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
147
+ hidden_states = hidden_states.transpose(1,2)
148
+ else:
149
+ # Self Attention
150
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
151
+ # Fully Connected
152
+ out = self.mlp(hidden_states)
153
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
154
+ return hidden_states
155
+
156
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
157
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
158
+ super().__init__()
159
+ self.layers = torch.nn.ModuleList(layers)
160
+
161
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
162
+ hidden_states = hidden_states + input_injection
163
+ for layer in self.layers:
164
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
165
+ return hidden_states
166
+
167
+
168
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
169
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
170
+ super().__init__()
171
+ self.config = config
172
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
173
+
174
+ # I/O
175
+
176
+ self.embed_scale = math.sqrt(self.config.hidden_size)
177
+ embed_init_std = 1.0 / self.embed_scale
178
+
179
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
180
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
181
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
182
+
183
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len # ceil div
184
+ if self.config.puzzle_emb_mode == "demo":
185
+ bank = np.load(self.config.demo_bank_path)
186
+ self.register_buffer("demo_in", torch.tensor(bank["demo_in"], dtype=torch.int32), persistent=False)
187
+ self.register_buffer("demo_out", torch.tensor(bank["demo_out"], dtype=torch.int32), persistent=False)
188
+ self.register_buffer("demo_valid", torch.tensor(bank["demo_valid"], dtype=torch.bool), persistent=False)
189
+ H = self.config.hidden_size
190
+ self.demo_type = nn.Parameter(trunc_normal_init_(torch.empty(2, H), std=embed_init_std))
191
+ self.demo_pos = nn.Parameter(trunc_normal_init_(torch.empty(self.config.seq_len, H), std=embed_init_std))
192
+ self.demo_queries = nn.Parameter(trunc_normal_init_(torch.empty(self.puzzle_emb_len, H), std=embed_init_std))
193
+ # cross-attention written out so the weights can be cast to forward_dtype at use
194
+ # (nn.MultiheadAttention keeps fp32 params and rejects bf16 inputs)
195
+ self.demo_q = CastedLinear(H, H, bias=False)
196
+ self.demo_kv = CastedLinear(H, 2 * H, bias=False)
197
+ self.demo_o = CastedLinear(H, H, bias=False)
198
+ self.demo_norm = nn.LayerNorm(H)
199
+ self.demo_mlp = nn.Sequential(nn.Linear(H, 4 * H), nn.GELU(), nn.Linear(4 * H, H))
200
+ if self.config.puzzle_emb_ndim > 0 and self.config.puzzle_emb_mode == "lookup":
201
+ # Zero init puzzle embeddings
202
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
203
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
204
+
205
+ # LM Blocks
206
+ if self.config.pos_encodings == "rope":
207
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
208
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
209
+ base=self.config.rope_theta)
210
+ elif self.config.pos_encodings == "learned":
211
+ self.embed_pos = CastedEmbedding(self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
212
+ else:
213
+ pass
214
+
215
+ # Reasoning Layers
216
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
217
+
218
+ # Initial states
219
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
220
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
221
+
222
+ # Fixed shared LoRA basis (see config.fast_lora_shared_A). Drawn from a PRIVATE
223
+ # generator: torch.randn(generator=g) does not advance the global RNG, so turning the
224
+ # flag on cannot shift halt_exploration's rand_like stream.
225
+ if self.config.fast_slice == "lora" and self.config.fast_lora_shared_A:
226
+ g = torch.Generator(device="cpu").manual_seed(0)
227
+ r = self.config.fast_lora_rank
228
+ for key, mod in self._fast_lora_targets():
229
+ in_f = mod.weight.shape[1]
230
+ self.register_buffer(
231
+ "fastA_" + key.replace(".", "__"),
232
+ torch.randn(in_f, r, generator=g, device="cpu") * (in_f ** -0.5),
233
+ persistent=True)
234
+
235
+ # Q head special init
236
+ # Init Q to (almost) zero for faster learning during bootstrapping
237
+ with torch.no_grad():
238
+ self.q_head.weight.zero_()
239
+ self.q_head.bias.fill_(-5) # type: ignore
240
+
241
+ def _demo_prefix(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
242
+ """[B, puzzle_emb_len, H] task prefix computed from the task's demonstration pairs.
243
+
244
+ A demo whose input grid equals THIS example's input is masked out, so a training row
245
+ that is itself one of the task's demos is encoded from the OTHER demos only -- the
246
+ model is trained to predict a demo it cannot see (leave-one-demo-out), which is the
247
+ within-task generalisation the lookup table never had to learn. No grid is ever
248
+ transformed or duplicated, so this is not augmentation.
249
+ """
250
+ din, dout, valid = self.demo_in[puzzle_identifiers], self.demo_out[puzzle_identifiers], self.demo_valid[puzzle_identifiers]
251
+ B, K, S = din.shape
252
+ valid = valid & ~(din == input.to(din.dtype).unsqueeze(1)).all(-1)
253
+ no_demo = ~valid.any(-1)
254
+ pos = self.demo_pos.to(self.forward_dtype)
255
+ e_in = self.embed_tokens(din) + pos + self.demo_type[0].to(self.forward_dtype)
256
+ e_out = self.embed_tokens(dout) + pos + self.demo_type[1].to(self.forward_dtype)
257
+ kv = torch.cat((e_in, e_out), 2).reshape(B, K * 2 * S, -1) # [B, K*2S, H]
258
+ pad = torch.cat((din == 0, dout == 0), 2).reshape(B, K * 2 * S) # pad tokens carry nothing
259
+ keymask = pad | ~valid.repeat_interleave(2 * S, dim=1)
260
+ keymask = keymask & ~keymask.all(-1, keepdim=True) # never mask an entire row (NaN guard)
261
+ nh, hd = self.config.num_heads, self.config.hidden_size // self.config.num_heads
262
+ q = self.demo_queries.to(self.forward_dtype).unsqueeze(0).expand(B, -1, -1)
263
+ Q = self.demo_q(q).view(B, -1, nh, hd).transpose(1, 2) # [B,nh,16,hd]
264
+ Kv = self.demo_kv(kv).view(B, kv.shape[1], 2, nh, hd)
265
+ Kx, Vx = Kv[:, :, 0].transpose(1, 2), Kv[:, :, 1].transpose(1, 2) # [B,nh,N,hd]
266
+ out = F.scaled_dot_product_attention(Q, Kx, Vx, attn_mask=(~keymask)[:, None, None, :]) # True = attend
267
+ out = self.demo_o(out.transpose(1, 2).reshape(B, -1, self.config.hidden_size))
268
+ out = out + self.demo_mlp(self.demo_norm(out.float())).to(out.dtype)
269
+ return out * self.embed_scale, no_demo
270
+
271
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor,
272
+ prev_pred: Optional[torch.Tensor] = None, ctx: Optional[torch.Tensor] = None):
273
+ # Token embedding
274
+ embedding = self.embed_tokens(input.to(torch.int32))
275
+
276
+ # SELF_COND (PREREG_Q2 §2q): input-side self-conditioning. The previous segment's
277
+ # argmax prediction (carried row-aligned in current_data["prev_pred"], detached) is
278
+ # embedded with the SAME token table and ADDED to the input embedding, before the
279
+ # puzzle prefix is concatenated. No new parameter is introduced, so every existing
280
+ # checkpoint still loads. Token 0 == pad == "no prediction", which is what a freshly
281
+ # reset row carries (the ACT wrapper's torch.where over current_data restores
282
+ # batch["prev_pred"], which the loss head fills with zeros). prev_pred is None unless
283
+ # the loss head put the key in the batch AND SELF_COND is set, so with SELF_COND
284
+ # unset this path is bit-for-bit the original.
285
+ if prev_pred is not None:
286
+ embedding = embedding + self.embed_tokens(prev_pred.to(torch.int32))
287
+
288
+ # Puzzle embeddings
289
+ if self.config.puzzle_emb_mode == "demo":
290
+ prefix, _ = self._demo_prefix(input, puzzle_identifiers)
291
+ embedding = torch.cat((prefix.to(embedding.dtype), embedding), dim=-2)
292
+ elif self.config.puzzle_emb_ndim > 0:
293
+ if ctx is not None:
294
+ # FAST SLICE "ctx": the per-sample slice replaces the lookup output entirely.
295
+ prefix = ctx.to(embedding.dtype)
296
+ else:
297
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
298
+
299
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
300
+ if pad_count > 0:
301
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
302
+ prefix = puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size)
303
+
304
+ embedding = torch.cat((prefix, embedding), dim=-2)
305
+
306
+ # Position embeddings
307
+ if self.config.pos_encodings == "learned":
308
+ # scale by 1/sqrt(2) to maintain forward variance
309
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
310
+
311
+ # Scale
312
+ return self.embed_scale * embedding
313
+
314
+ def empty_carry(self, batch_size: int):
315
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
316
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
317
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
318
+ )
319
+
320
+ def _fast_lora_targets(self):
321
+ """Ordered (key, module) of the channel-MLP projections a "lora" fast slice adapts."""
322
+ return [(f"{i}.{name}", getattr(layer.mlp, name))
323
+ for i, layer in enumerate(self.L_level.layers)
324
+ for name in ("gate_up_proj", "down_proj")]
325
+
326
+ @torch.no_grad()
327
+ def init_phi(self, batch_size: int, device):
328
+ """Fresh per-sample fast slice, initialised so the model is identical to the base model.
329
+
330
+ "ctx": per-sample copy of the puzzle-embedding lookup row 0 (padded/reshaped exactly as
331
+ the lookup output is). "lora": A ~ N(0, 1/in), B = 0, so the delta is zero.
332
+ """
333
+ mode = self.config.fast_slice
334
+ if mode == "ctx":
335
+ assert hasattr(self, "puzzle_emb"), "fast_slice=ctx needs puzzle_emb_ndim>0 and puzzle_emb_mode=lookup"
336
+ w = self.puzzle_emb.weights[0]
337
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - w.shape[-1]
338
+ if pad_count > 0:
339
+ w = F.pad(w, (0, pad_count))
340
+ ctx = w.view(1, self.puzzle_emb_len, self.config.hidden_size).to(device=device, dtype=self.forward_dtype)
341
+ return {"ctx": ctx.expand(batch_size, -1, -1).contiguous()}
342
+ if mode == "lora":
343
+ r = self.config.fast_lora_rank
344
+ lora = {}
345
+ shared = self.config.fast_lora_shared_A
346
+ for key, mod in self._fast_lora_targets():
347
+ out_f, in_f = mod.weight.shape
348
+ if shared:
349
+ a = getattr(self, "fastA_" + key.replace(".", "__")).to(
350
+ device=device, dtype=self.forward_dtype).unsqueeze(0).expand(batch_size, -1, -1).contiguous()
351
+ else:
352
+ a = torch.randn(batch_size, in_f, r, device=device, dtype=self.forward_dtype) * (in_f ** -0.5)
353
+ lora[key] = (a, torch.zeros(batch_size, r, out_f, device=device, dtype=self.forward_dtype))
354
+ return {"lora": lora}
355
+ raise ValueError(f"unknown fast_slice {mode!r}")
356
+
357
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
358
+ H_init, L_init = self.H_init, self.L_init
359
+ hinit_noise = os.environ.get("HINIT_NOISE")
360
+ if hinit_noise and self.training:
361
+ sigma = float(hinit_noise)
362
+ H_init = H_init + sigma * H_init.std() * torch.randn_like(carry.z_H)
363
+ L_init = L_init + sigma * L_init.std() * torch.randn_like(carry.z_L)
364
+ phi = carry.phi
365
+ if phi is not None and not self.config.fast_slice_external_reset and bool(reset_flag.any()):
366
+ # a halted row's fast slice goes back to its init, exactly like z_H/z_L
367
+ init = self.init_phi(carry.z_H.shape[0], carry.z_H.device)
368
+ flag = reset_flag.view(-1, 1, 1)
369
+ if "ctx" in phi:
370
+ phi = {"ctx": torch.where(flag, init["ctx"], phi["ctx"])}
371
+ else:
372
+ phi = {"lora": {k: (torch.where(flag, init["lora"][k][0], a), torch.where(flag, init["lora"][k][1], b))
373
+ for k, (a, b) in phi["lora"].items()}}
374
+ z_H = torch.where(reset_flag.view(-1, 1, 1), H_init, carry.z_H)
375
+ z_L = torch.where(reset_flag.view(-1, 1, 1), L_init, carry.z_L)
376
+ if self.training and self.config.train_init_noise > 0: # §2ck K1: the odd rows being reset start at random
377
+ odd = (reset_flag & (torch.arange(reset_flag.shape[0], device=reset_flag.device) % 2 == 1)).view(-1, 1, 1)
378
+ z_H = torch.where(odd, self.config.train_init_noise * torch.randn_like(z_H), z_H)
379
+ z_L = torch.where(odd, self.config.train_init_noise * torch.randn_like(z_L), z_L)
380
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H, z_L=z_L, phi=phi)
381
+
382
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
383
+ seq_info = dict(
384
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
385
+ )
386
+
387
+ # Input encoding
388
+ prev_pred = batch.get("prev_pred") if os.environ.get("SELF_COND") else None
389
+ phi = carry.phi or {}
390
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], prev_pred, ctx=phi.get("ctx"))
391
+
392
+ # Forward iterations
393
+ it = 0
394
+ z_H, z_L = carry.z_H, carry.z_L
395
+ lora = phi.get("lora")
396
+ lora_ctx = {id(mod): lora[key] for key, mod in self._fast_lora_targets()} if lora is not None else None
397
+ try:
398
+ if lora_ctx is not None:
399
+ set_fast_lora(lora_ctx)
400
+ # H_cycles-1 without grad
401
+ with torch.no_grad():
402
+ for _H_step in range(self.config.H_cycles-1):
403
+ for _L_step in range(self.config.L_cycles):
404
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
405
+ z_H = self.L_level(z_H, z_L, **seq_info)
406
+ # 1 with grad
407
+ for _L_step in range(self.config.L_cycles):
408
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
409
+ z_H = self.L_level(z_H, z_L, **seq_info)
410
+ finally:
411
+ if lora_ctx is not None:
412
+ set_fast_lora(None)
413
+
414
+ # LM Outputs
415
+ # Default: detach the carry every segment (original TRM/HRM "1-step gradient"
416
+ # design -- memory-cheap, but a later segment's loss can never influence an
417
+ # earlier segment's parameter update). KEEP_GRAD_CARRY=1 skips the detach so an
418
+ # external training loop can connect gradient across a window of consecutive
419
+ # segments before detaching itself; unset, behavior is bit-for-bit identical to
420
+ # every existing checkpoint in this repo.
421
+ if os.environ.get("KEEP_GRAD_CARRY"):
422
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H, z_L=z_L, phi=carry.phi)
423
+ else:
424
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach(), phi=carry.phi) # New carry no grad
425
+ if self.training and self.config.train_step_noise > 0: # §2ck K1: path noise on the carried z_H only (outputs stay clean)
426
+ c = new_carry.z_H
427
+ rms = c.detach().float().square().mean(dim=(1, 2), keepdim=True).sqrt()
428
+ new_carry.z_H = (c + self.config.train_step_noise * rms * torch.randn_like(c, dtype=torch.float32)).to(c.dtype)
429
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
430
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
431
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1]), z_H # z_H: solved-state target (losses.SolvedTargetLossHead)
432
+
433
+
434
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
435
+ """ACT wrapper."""
436
+
437
+ def __init__(self, config_dict: dict):
438
+ super().__init__()
439
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
440
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
441
+
442
+ @property
443
+ def puzzle_emb(self):
444
+ return self.inner.puzzle_emb
445
+
446
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
447
+ batch_size = batch["inputs"].shape[0]
448
+
449
+ inner_carry = self.inner.empty_carry(batch_size)
450
+ if self.config.fast_slice in ("ctx", "lora"):
451
+ # phi is data, not a parameter: an adaptation loop sets requires_grad on it itself.
452
+ inner_carry.phi = self.inner.init_phi(batch_size, inner_carry.z_H.device)
453
+
454
+ steps = torch.zeros((batch_size, ), dtype=torch.int32)
455
+ if self.training and not self.config.act_halt:
456
+ # Walk mode: every episode lasts exactly H = halt_max_steps segments, so rows that start together stay in
457
+ # lockstep and every batch would sit at ONE segment for the whole run. Only the FIRST episode is staggered:
458
+ # steps = -o (o = H-1 - i mod H), which forward's reset turns into a start at segment o+1, so row i's first
459
+ # episode lasts (i mod H)+1 segments, every later one H, and each batch holds every segment equally often.
460
+ # (That first episode starts from the fresh carry at segment index o+1: a one-episode transient.)
461
+ H = self.config.halt_max_steps
462
+ steps = torch.arange(batch_size, dtype=torch.int32) % H - (H - 1)
463
+
464
+ return TinyRecursiveReasoningModel_ACTV1Carry(
465
+ inner_carry=inner_carry, # Empty is expected, it will be reseted in first pass as all sequences are halted.
466
+
467
+ steps=steps,
468
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
469
+
470
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
471
+ )
472
+
473
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
474
+
475
+ # Update data, carry (removing halted sequences)
476
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
477
+
478
+ new_steps = torch.where(carry.halted, (-carry.steps).clamp_min(0), carry.steps) # 0, or initial_carry's stagger o
479
+
480
+ new_current_data = {k: torch.where(carry.halted.view((-1, ) + (1, ) * (batch[k].ndim - 1)), batch[k], v) for k, v in carry.current_data.items()}
481
+
482
+ # Forward inner model
483
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits), z_H = self.inner(new_inner_carry, new_current_data)
484
+
485
+ outputs = {
486
+ "logits": logits,
487
+ "z_H": z_H[:, self.inner.puzzle_emb_len:],
488
+ "q_halt_logits": q_halt_logits,
489
+ "q_continue_logits": q_continue_logits
490
+ }
491
+
492
+ with torch.no_grad():
493
+ # Step
494
+ new_steps = new_steps + 1
495
+ is_last_step = new_steps >= self.config.halt_max_steps
496
+
497
+ halted = is_last_step
498
+
499
+ # if training, and ACT is enabled
500
+ if self.training and (self.config.halt_max_steps > 1):
501
+
502
+ if self.config.act_halt: # (else: the walk, halted stays is_last_step)
503
+ # Halt signal
504
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
505
+
506
+ if self.config.no_ACT_continue:
507
+ halted = halted | (q_halt_logits > 0)
508
+ else:
509
+ halted = halted | (q_halt_logits > q_continue_logits)
510
+
511
+ # Exploration
512
+ min_halt_steps = (torch.rand_like(q_halt_logits) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
513
+ halted = halted & (new_steps >= min_halt_steps)
514
+
515
+ if not self.config.no_ACT_continue:
516
+ # Compute target Q
517
+ # NOTE: No replay buffer and target networks for computing target Q-value.
518
+ # As batch_size is large, there're many parallel envs.
519
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
520
+ _, _, (next_q_halt_logits, next_q_continue_logits), _ = self.inner(new_inner_carry, new_current_data)
521
+ outputs["target_q_continue"] = torch.sigmoid(torch.where(is_last_step, next_q_halt_logits, torch.maximum(next_q_halt_logits, next_q_continue_logits)))
522
+
523
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/all_config.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 128
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9S
16
+ no_ACT_continue: true
17
+ num_heads: 4
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 0
20
+ puzzle_emb_ndim: 1280
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0
25
+ data_paths:
26
+ - data/arc_a9p1
27
+ data_paths_test: []
28
+ ema: false
29
+ ema_rate: 0.999
30
+ epochs: 1422
31
+ eval_interval: 1422
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 64
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 200
40
+ min_eval_interval: 0
41
+ project_name: Arc1concept-aug-0-ACT-torch
42
+ puzzle_emb_lr: 0.01
43
+ puzzle_emb_weight_decay: 0.1
44
+ run_name: trm_arc1_a9p1s_s0
45
+ sam_rho: 0.0
46
+ seed: 0
47
+ weight_decay: 0.1
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/losses.py ADDED
The diff for this file is too large to render. See raw diff
 
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/step_3000 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5fe96e52b5fcdb1e382114bf5589df65497f4a126bea56ef17a708b72edbdb2
3
+ size 7556443
trm_ckpt/Arc1concept-aug-0-ACT-torch/trm_arc1_a9p1s_s0/trm_a9.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PREREG_Q2 §2cr a9: an ARC TRM body that is exactly equivariant to permutations of colours 1..9 (S9) and invariant to
2
+ where the grid sits on the 30 x 30 canvas.
3
+
4
+ Why: on no-aug ARC the plain body with WALK stops memorising (.94 -> .26 on train demos) but learns no rule and finds no fixed
5
+ points (C-Q2-157); on Sudoku the judge and the self-training rest on an equivariant body (C-Q2-151/152/155). Colour 0 (background)
6
+ stays special -- ARC treats it so -- hence S9, not S10:
7
+ logits(pi . x, pi . e) = pi . logits(x, e) for pi fixing colour 0 (core/tests/smoke_a9.py (a); e = the task table)
8
+
9
+ Tokens: 900 cells x 10 colour slots = 9,000, COLOUR-MAJOR (hidden [B, 10*900, D] == [B, 10, 900, D]), no puzzle prefix. Slot k of
10
+ a cell is embedded from its type w.r.t. colour k (token 2 + k): {pad, EOS, colour == k, another colour}; slot 0 also gets a learned
11
+ background flag. The task embedding is the parent's sparse puzzle_emb (same SignSGD optimiser, lr and weight decay in pretrain.py)
12
+ at width 10 * D, read as one D-vector per colour slot and added to that slot of every cell at every input injection.
13
+ Block (post-norm, the S9Block frame): (i) per-slot attention over the 900 cells, one weight set for all slots, the parent's 1D RoPE
14
+ (the parent's self_attn: mlp_t=false); (ii) + (iii) = S9Block.mix_digits_channels: position-free attention over each cell's 10
15
+ slots, then the channel SwiGLU.
16
+ Output: per cell token 0 (pad) = -1e4, token 1 (EOS) = a linear read of the mean over the 10 slots, token 2 + k = slot k's scalar;
17
+ Q head on the mean over all 9,000 tokens.
18
+ Translation: forward moves each row's INPUT so its first row / column holding a token >= 1 lands on (0, 0) (a cyclic roll; the
19
+ rolled-in cells are pad) and rolls the logits back; the carry and z_H live in the aligned frame. The builder puts a pair's input
20
+ and label at the same offset (all 3,988 arc1concept-aug-0 train rows; 74% are offset), so label cells never wrap, the body is
21
+ exactly translation-invariant (smoke (c)) and the builder's random offsets carry no signal. Everything else (ACT wrapper,
22
+ carry, reset, H/L cycles, no-grad cycles, detach, walk) is the parent trm.py code.
23
+
24
+ arch.name=recursive_reasoning.trm_a9@TinyRecursiveReasoningModel_A9 with arch.puzzle_emb_ndim = 10 * hidden_size,
25
+ arch.puzzle_emb_len=0, arch.pos_encodings=rope, arch.mlp_t=false; ...@TinyRecursiveReasoningModel_A9S = a9s (§2cr 정정 3 v1), a class
26
+ and not an arch key because the parent's pydantic config drops unknown keys silently.
27
+ """
28
+ import os
29
+ from typing import Dict
30
+
31
+ import torch
32
+
33
+ from models.layers import rms_norm, CastedEmbedding, CastedLinear, RotaryEmbedding
34
+ from models.recursive_reasoning.trm import (
35
+ TinyRecursiveReasoningModel_ACTV1Config, TinyRecursiveReasoningModel_ACTV1ReasoningModule,
36
+ TinyRecursiveReasoningModel_ACTV1_Inner, TinyRecursiveReasoningModel_ACTV1InnerCarry)
37
+ from models.recursive_reasoning.trm_s9 import S9Block, TinyRecursiveReasoningModel_S9
38
+
39
+ N_COL, SIDE = 10, 30 # colour slots (token 2 + k = colour k; 1 = EOS, 0 = pad); the canvas side
40
+
41
+
42
+ def shift(t: torch.Tensor, r: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
43
+ """t [B, 900, ...] -> t' with t'[b, (i, j)] = t[b, ((i + r_b) % 30, (j + c_b) % 30)] (a per-row cyclic roll by (-r_b, -c_b))."""
44
+ B, i = t.shape[0], torch.arange(SIDE, device=t.device)
45
+ rows, cols = ((i + r.view(B, 1)) % SIDE).view(B, SIDE, 1), ((i + c.view(B, 1)) % SIDE).view(B, 1, SIDE)
46
+ return t.view(B, SIDE, SIDE, *t.shape[2:])[torch.arange(B, device=t.device).view(B, 1, 1), rows, cols].view(t.shape)
47
+
48
+
49
+ class A9Block(S9Block):
50
+ """(i) cell attention per colour slot (shared weights, RoPE) -> S9Block's (ii) slot attention + (iii) channel MLP."""
51
+
52
+ def forward(self, cos_sin, hidden_states: torch.Tensor) -> torch.Tensor:
53
+ B, T, D = hidden_states.shape
54
+ h = hidden_states.view(B * N_COL, T // N_COL, D)
55
+ h = rms_norm(h + self.self_attn(cos_sin=cos_sin, hidden_states=h), variance_epsilon=self.norm_eps)
56
+ return self.mix_digits_channels(h.view(B, N_COL, T // N_COL, D))
57
+
58
+
59
+ class A9LMHead(torch.nn.Module):
60
+ """[B, 10*900, D] -> vocab logits [B, 900, 12]: pad -1e4, EOS from the slot mean, token 2 + k from slot k."""
61
+
62
+ def __init__(self, hidden_size: int) -> None:
63
+ super().__init__()
64
+ self.slot, self.eos = CastedLinear(hidden_size, 1, bias=False), CastedLinear(hidden_size, 1, bias=False)
65
+
66
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
67
+ z = z.view(z.shape[0], N_COL, -1, z.shape[-1])
68
+ col = self.slot(z)[..., 0].transpose(1, 2) # [B, 900, 10]
69
+ return torch.cat((col.new_full(col.shape[:2] + (1,), -1e4), self.eos(z.mean(1)), col), dim=-1)
70
+
71
+
72
+ class TinyRecursiveReasoningModel_A9_Inner(TinyRecursiveReasoningModel_ACTV1_Inner):
73
+ task_raw = False # a9s (§2cr 정정 3 v1): the task vector added after embed_scale, at the table's raw scale
74
+
75
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
76
+ D = config.hidden_size
77
+ assert config.seq_len == SIDE * SIDE and config.vocab_size == N_COL + 2, "a9: ARC only (30 x 30, vocab 12)"
78
+ assert config.puzzle_emb_ndim == N_COL * D and config.puzzle_emb_len == 0 and config.puzzle_emb_mode == "lookup", \
79
+ "a9: puzzle_emb_ndim = 10 * hidden_size (one task vector per colour slot), puzzle_emb_len=0"
80
+ assert config.pos_encodings == "rope" and not config.mlp_t and config.fast_slice is None, "a9: rope, mlp_t=false, no fast slice"
81
+ assert not os.environ.get("SELF_COND"), "a9: SELF_COND is not supported"
82
+ super().__init__(config)
83
+ # the parent sized a ceil(ndim / D) = 10-slot prefix (the wrapper's z_H slice, the output slice, RoPE): a9 has none
84
+ self.puzzle_emb_len = 0
85
+ self.rotary_emb = RotaryEmbedding(dim=D // config.num_heads, max_position_embeddings=config.seq_len, base=config.rope_theta)
86
+ del self.embed_tokens
87
+ self.embed_types = CastedEmbedding(5, D, init_std=1.0 / self.embed_scale, cast_to=self.forward_dtype) # 4 types + bg flag
88
+ self.lm_head = A9LMHead(D)
89
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[A9Block(config) for _i in range(config.L_layers)])
90
+
91
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, prev_pred=None, ctx=None):
92
+ # slot k's type at a cell: 0 pad, 1 EOS, 2 colour == k, 3 another colour; row 4 of the table = slot 0's background flag
93
+ x, k = input.unsqueeze(1), torch.arange(2, 2 + N_COL, device=input.device).view(1, N_COL, 1)
94
+ types = torch.where(x < 2, x, torch.where(x == k, 2, 3)).to(torch.int32) # [B, 10, 900]
95
+ bg = (k == 2).unsqueeze(-1) * self.embed_types.embedding_weight[4].to(self.forward_dtype) # [1, 10, 1, D]
96
+ task = self.puzzle_emb(puzzle_identifiers).view(-1, N_COL, 1, self.config.hidden_size)
97
+ e = self.embed_types(types) + bg
98
+ return (self.embed_scale * e + task if self.task_raw else self.embed_scale * (e + task)).flatten(1, 2)
99
+
100
+ def empty_carry(self, batch_size: int):
101
+ shape = (batch_size, N_COL * self.config.seq_len, self.config.hidden_size)
102
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=torch.empty(shape, dtype=self.forward_dtype),
103
+ z_L=torch.empty(shape, dtype=self.forward_dtype))
104
+
105
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]):
106
+ x = batch["inputs"]
107
+ g = (x >= 1).view(-1, SIDE, SIDE)
108
+ r0, c0 = g.any(2).int().argmax(1), g.any(1).int().argmax(1) # the anchor; (0, 0) for an all-pad row
109
+ new_carry, out, _, z_H = super().forward(carry, dict(batch, inputs=shift(x, r0, c0)))
110
+ q_logits = self.q_head(z_H.mean(dim=1)).to(torch.float32) # permutation-invariant Q (s9's)
111
+ return new_carry, shift(out, -r0, -c0), (q_logits[..., 0], q_logits[..., 1]), z_H
112
+
113
+
114
+ class TinyRecursiveReasoningModel_A9(TinyRecursiveReasoningModel_S9):
115
+ """ACT wrapper driving the a9 inner (§2cr)."""
116
+ inner_cls = TinyRecursiveReasoningModel_A9_Inner
117
+
118
+
119
+ class TinyRecursiveReasoningModel_A9S_Inner(TinyRecursiveReasoningModel_A9_Inner):
120
+ task_raw = True
121
+
122
+
123
+ class TinyRecursiveReasoningModel_A9S(TinyRecursiveReasoningModel_A9):
124
+ """a9s: the input embedding embed_scale * (types + bg) + task (a9: embed_scale * (types + bg + task)), the table at its raw scale."""
125
+ inner_cls = TinyRecursiveReasoningModel_A9S_Inner