revision/: clue-matched evaluation, measured FLOPs (runs in progress)
Browse filesFiles changed (33)
- revision/README.mdAdded+84
- revision/clue_sets/data/sudoku_c30/test_puz.npyAdded+3
- revision/clue_sets/data/sudoku_c30/test_sol.npyAdded+3
- revision/clue_sets/data/sudoku_c35/test_puz.npyAdded+3
- revision/clue_sets/data/sudoku_c35/test_sol.npyAdded+3
- revision/clue_sets/data/sudoku_c40/test_puz.npyAdded+3
- revision/clue_sets/data/sudoku_c40/test_sol.npyAdded+3
- revision/clue_sets/results/ncm_same_data_old_c30.jsonAdded+11
- revision/clue_sets/results/ncm_same_data_old_c35.jsonAdded+11
- revision/clue_sets/results/ncm_same_data_old_c40.jsonAdded+11
- revision/clue_sets/results/ncm_same_data_old_hard.jsonAdded+11
- revision/clue_sets/results/ncm_sudoku-easy_c40.jsonAdded+36
- revision/clue_sets/results/ncm_sudoku-hard_c30.jsonAdded+36
- revision/clue_sets/results/ncm_sudoku-hard_ours.jsonAdded+64
- revision/clue_sets/results/ncm_sudoku-medium_c35.jsonAdded+36
- revision/clue_sets/results/ours_rec_full_c30_K1.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c30_K12.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c30_K61.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c35_K1.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c35_K12.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c35_K61.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c40_K1.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c40_K12.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_c40_K61.jsonAdded+21
- revision/clue_sets/results/ours_rec_full_hard_K1.jsonAdded+49
- revision/clue_sets/results/ours_rec_full_hard_K12.jsonAdded+49
- revision/clue_sets/results/ours_rec_full_hard_K61.jsonAdded+49
- revision/code/count_flops.pyAdded+119
- revision/code/eval_same_data.pyAdded+51
- revision/code/make_clue_sets.pyAdded+129
- revision/code/train_same_data.pyAdded+378
- revision/code/train_sudoku.pyAdded+319
- revision/compute/compute_flops.jsonAdded+25
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Revision experiments — Recursive Masked Diffusion on Sudoku (MSML612)
Experiments run in December 2026 in response to reviewer comments, on one rented NVIDIA A100-SXM4-40GB (Lambda Cloud, budget capped at $50). Every number below is read from a result file in this directory. Nothing here replaces the original runs elsewhere in the repository; it adds to them.
| reviewer issue | what was run | section ||---|---|---|| NCM comparison inconclusive (stopped at 22,405 / 50,000 updates) | NCM-on-our-data run resumed from its checkpoint to the full 50,000 updates | [1](#1-ncm-trained-on-our-data) || Published NCM evaluated out of distribution | Test sets at NCM's own clue counts (40 / 35 / 30); every model scored on them | [2](#2-distribution-shift-ncms-own-difficulty-levels) || Unequal training and inference budgets | Training and inference FLOPs measured for both models | [3](#3-compute-measured) || Limited seeds | Second seed of the injection-ON arm (§2b) and of the 32-layer arm | [4](#4-additional-seeds) || Failed reproduction of the Recurrent Transformer | Our model on the RRN benchmark that the Recurrent Transformer reports on | [5](#5-the-rrn-benchmark) |
## 1. NCM trained on our data
The official NCM modules (HazyResearch/ncm @ `af2cf6f`), randomly initialised and trained on our 100,000 training puzzles with our training loop. The first run stopped at 22,405 of 50,000 generator updates with its learning rate still at 1.9e-4; it is resumed here from its saved model, optimizer and RNG state, on the same cosine schedule, to the full 50,000 (batch 256; the paper's 1,024 was not affordable).
| test set | clues | 22,405 updates | 50,000 updates ||---|---|---|---|| NCM level | 40 | 94.2% | *running* || NCM level | 35 | 71.2% | *running* || NCM level | 30 | 26.7% | *running* || our benchmark | 21–28 (ours) | 2.2% | *running* |
The 22,405-update model scored 2.4% on our test set when first evaluated and 2.2% when re-evaluated here on a different A100 (greedy decoding; the 2-puzzle difference is bf16 kernel nondeterminism). Accuracy falls steeply with clue count: NCM trained on our data learns Sudoku, and fails where the puzzles become hard.
## 2. Distribution shift: NCM's own difficulty levels
1,000 puzzles at each of NCM's fixed clue counts, generated by `code/make_clue_sets.py` with the same solution sampler and per-removal uniqueness check as our benchmark, seeds disjoint from training (0 / 1,000 solutions shared with our training split, up to digit relabelling). The published NCM checkpoints reproduce their paper on these sets, which validates them.
| test set | published NCM (paper) | NCM on our data, 50k | ours, 1 pass | ours, 12 passes | ours, 61 passes ||---|---|---|---|---|---|| 40 clues (`sudoku-easy`) | 99.1% (99.5) | *running* | 100.0% | 100.0% | 100.0% || 35 clues (`sudoku-medium`) | 96.1% (96.5) | *running* | 100.0% | 99.9% | 99.9% || 30 clues (`sudoku-hard`) | 86.6% (86.1) | *running* | 99.9% | 99.8% | 99.9% || ours, 21–28 clues | 30.4% (–) | *running* | 97.3% | 98.9% | 99.7% |
Ours is `rec1-full-s0` (212k parameters), trained only on our benchmark's training split (20–30 clues, mean 24.4). NCM's 35- and 40-clue levels lie outside that range on the easy side; 30 clues is at its edge. At NCM's hardest level, which is NCM's own training distribution, the published 25M-parameter checkpoint scores 86.6% and ours 99.9% at one pass. The reverse direction is in §1: NCM trained on our split falls to a few percent on our test set.
## 3. Compute, measured
Counted with `torch.utils.flop_counter` on the real training and decoding code (`code/count_flops.py`).
| | params | training FLOPs | inference GFLOP / puzzle ||---|---|---|---|| ours, `rec1-full` (120k steps × 256) | 212k | 0.21 EFLOP (1×) | 2.3 at 1 pass · 27.2 at 12 · 131 at 61 || NCM on our data, 22,405 updates | 25.5M + 14.9M codec | 0.42 EFLOP (2.0×) | 22.4 (12 levels, KV cache) || NCM on our data, 50,000 updates | 25.5M + 14.9M codec | 0.94 EFLOP (4.5×) | 22.4 || NCM, paper budget (batch 1,024) | 25.5M + 14.9M codec | 3.77 EFLOP (18×) | 22.4 |
NCM trained on our data received more training compute than our model even when it stopped early. At 12 passes our inference cost is within 1.2× of NCM's; at one pass it is 10× lower.
## 4. Additional seeds
| arm | original | new seed | config ||---|---|---|---|| §2b R-MDM + input injection ON | 96.90% @61 NFE (n=1) | *running* | batch 64, stopped at step 80,000 of 110,000 like the other arms || 32 distinct layers @bs256 | 94.50% (n=1) | *running* | d128, 32 layers, batch 256, 120k steps |
## 5. The RRN benchmark
RRN's `sudoku-hard` split (Palm et al., NeurIPS 2018): 180k train / 18k test, 17–34 clues. Yang et al. (ICLR 2023) report 99.5% for the Recurrent Transformer here at 211k parameters, the same size and shape (d128, 1 block, R=32) as ours. Our reimplementation of their *direct classifier* reached only 31% on our benchmark (README §2), so instead of comparing against it we put our model on their benchmark.
| model | trained on | 1 pass | 12 passes | 61 passes ||---|---|---|---|---|| ours `rec1-full-s0` (zero-shot) | our benchmark | *running* | – | *running* || ours, same recipe | RRN train | *running* | *running* | *running* || Recurrent Transformer (Yang et al., 2023, reported) | RRN train | – | – | 99.5% |
## Problems found and fixed during these runs
- **Clue-set generator reproduced the training split.** `make_clue_sets.py` defaulted to seed 0, and `gen_hard_sudoku.py` drew the training split from seeds 0–100,999 with the same solution sampler, so every generated solution was a training solution. The leakage assertion caught it before anything was scored; the default is now 1,000,000 × clues.- **NCM trainer had no resume path.** `train_same_data.py --resume-from` restores the trained tokenizer and the generator's model, optimizer and RNG state and continues the same learning-rate schedule.- **Full evaluation sweep is too slow for an 18k-puzzle test set** (~570 passes per puzzle). `train_sudoku.py --skip_final_eval` saves the model and leaves scoring to `eval_ours.py`.
## Files
| path | contents ||---|---|| `clue_sets/data/` | the 40 / 35 / 30-clue test sets (1,000 puzzles each) || `clue_sets/results/` | every model on every set (`_K<passes>` for ours) || `compute/compute_flops.json` | measured FLOPs || `ncm-same-data-s0-resumed/` | resumed NCM run: weights, training curves, manifest, predictions || `rmdm-both-s1/`, `abl-deep32L-s1/`, `rrn/` | new seeds and the RRN runs: weights, logs, results || `code/` | the scripts as run, including the fixes above |123version https://git-lfs.github.com/spec/v1oid sha256:92a78132481283011649263321af2d4715e85cce2c3bbea33e690441819e7b25size 81128123version https://git-lfs.github.com/spec/v1oid sha256:cfbcb778bdce6580b2e7662be60e1c52d5b4a0ee38c9abaae21e85b3b3f94380size 81128123version https://git-lfs.github.com/spec/v1oid sha256:6430a9e4f8dfcd9a3441f88bb2145bea00bc72c554862f4b1889e351c3b246f3size 81128123version https://git-lfs.github.com/spec/v1oid sha256:784c561e09ffc5f519acfb13346a58488400a410872835b464f7791f67d57e27size 81128123version https://git-lfs.github.com/spec/v1oid sha256:1b70e454d5173ddc6c21ea9514a9851ac2d88ad882cab2cb3bdf5e889b32af2csize 81128123version https://git-lfs.github.com/spec/v1oid sha256:3fcc8f6fae77e64d444ec9a76f7d4d273173815dc6a0a62980374fdca142fe60size 811281234567891011{ "n": 1000, "nfe": 12, "board_accuracy": 0.267, "legal_rate": 0.268, "clue_consistent_rate": 0.971, "separator_correct_rate": 1.0, "run": "prev", "generator_step": 22405, "test_set": "sudoku_c30"}1234567891011{ "n": 1000, "nfe": 12, "board_accuracy": 0.712, "legal_rate": 0.714, "clue_consistent_rate": 0.992, "separator_correct_rate": 1.0, "run": "prev", "generator_step": 22405, "test_set": "sudoku_c35"}1234567891011{ "n": 1000, "nfe": 12, "board_accuracy": 0.942, "legal_rate": 0.942, "clue_consistent_rate": 0.998, "separator_correct_rate": 1.0, "run": "prev", "generator_step": 22405, "test_set": "sudoku_c40"}1234567891011{ "n": 1000, "nfe": 12, "board_accuracy": 0.022, "legal_rate": 0.022, "clue_consistent_rate": 0.942, "separator_correct_rate": 1.0, "run": "prev", "generator_step": 22405, "test_set": "sudoku_hard"}123456789101112131415161718192021222324252627282930313233343536{ "task": "sudoku-easy", "repo": "mrfakename/ncm-webgpu-weights", "device": "CPUExecutionProvider", "data": "/home/ubuntu/w/data/sudoku_c40", "split": "test", "n": 1000, "nfe": 12, "levels": [ 1, 2, 4, 6, 9, 13, 18, 26, 37, 50, 67, 89 ], "board_accuracy": 0.991, "legal_rate": 0.991, "clue_consistent_rate": 0.998, "clues_min": 40, "clues_max": 40, "clues_mean": 40.0, "by_clue": { "40": { "n": 1000, "board": 991 } }, "seconds": 356.8956570625305}123456789101112131415161718192021222324252627282930313233343536{ "task": "sudoku-hard", "repo": "mrfakename/ncm-webgpu-weights", "device": "CPUExecutionProvider", "data": "/home/ubuntu/w/data/sudoku_c30", "split": "test", "n": 1000, "nfe": 12, "levels": [ 1, 2, 4, 6, 9, 13, 18, 26, 37, 50, 67, 89 ], "board_accuracy": 0.866, "legal_rate": 0.867, "clue_consistent_rate": 0.999, "clues_min": 30, "clues_max": 30, "clues_mean": 30.0, "by_clue": { "30": { "n": 1000, "board": 866 } }, "seconds": 416.7448728084564}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "task": "sudoku-hard", "repo": "mrfakename/ncm-webgpu-weights", "device": "CPUExecutionProvider", "data": "/home/ubuntu/w/data/sudoku_hard", "split": "test", "n": 1000, "nfe": 12, "levels": [ 1, 2, 4, 6, 9, 13, 18, 26, 37, 50, 67, 89 ], "board_accuracy": 0.304, "legal_rate": 0.304, "clue_consistent_rate": 0.991, "clues_min": 21, "clues_max": 28, "clues_mean": 24.318, "by_clue": { "21": { "n": 3, "board": 2 }, "22": { "n": 43, "board": 8 }, "23": { "n": 181, "board": 51 }, "24": { "n": 345, "board": 107 }, "25": { "n": 282, "board": 95 }, "26": { "n": 127, "board": 38 }, "27": { "n": 18, "board": 3 }, "28": { "n": 1, "board": 0 } }, "seconds": 352.1783277988434}123456789101112131415161718192021222324252627282930313233343536{ "task": "sudoku-medium", "repo": "mrfakename/ncm-webgpu-weights", "device": "CPUExecutionProvider", "data": "/home/ubuntu/w/data/sudoku_c35", "split": "test", "n": 1000, "nfe": 12, "levels": [ 1, 2, 4, 6, 9, 13, 18, 26, 37, 50, 67, 89 ], "board_accuracy": 0.961, "legal_rate": 0.961, "clue_consistent_rate": 0.992, "clues_min": 35, "clues_max": 35, "clues_mean": 35.0, "by_clue": { "35": { "n": 1000, "board": 961 } }, "seconds": 375.23803901672363}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c30", "split": "test", "n": 1000, "nfe": 1, "seed": 0, "board_accuracy": 0.999, "clues_min": 30, "clues_max": 30, "clues_mean": 30.0, "by_clue": { "30": { "n": 1000, "board": 999 } }, "seconds": 1.6688158512115479}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c30", "split": "test", "n": 1000, "nfe": 12, "seed": 0, "board_accuracy": 0.998, "clues_min": 30, "clues_max": 30, "clues_mean": 30.0, "by_clue": { "30": { "n": 1000, "board": 998 } }, "seconds": 14.73189640045166}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c30", "split": "test", "n": 1000, "nfe": 61, "seed": 0, "board_accuracy": 0.999, "clues_min": 30, "clues_max": 30, "clues_mean": 30.0, "by_clue": { "30": { "n": 1000, "board": 999 } }, "seconds": 60.29737973213196}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c35", "split": "test", "n": 1000, "nfe": 1, "seed": 0, "board_accuracy": 1.0, "clues_min": 35, "clues_max": 35, "clues_mean": 35.0, "by_clue": { "35": { "n": 1000, "board": 1000 } }, "seconds": 1.6525886058807373}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c35", "split": "test", "n": 1000, "nfe": 12, "seed": 0, "board_accuracy": 0.999, "clues_min": 35, "clues_max": 35, "clues_mean": 35.0, "by_clue": { "35": { "n": 1000, "board": 999 } }, "seconds": 14.806987285614014}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c35", "split": "test", "n": 1000, "nfe": 61, "seed": 0, "board_accuracy": 0.999, "clues_min": 35, "clues_max": 35, "clues_mean": 35.0, "by_clue": { "35": { "n": 1000, "board": 999 } }, "seconds": 59.11043882369995}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c40", "split": "test", "n": 1000, "nfe": 1, "seed": 0, "board_accuracy": 1.0, "clues_min": 40, "clues_max": 40, "clues_mean": 40.0, "by_clue": { "40": { "n": 1000, "board": 1000 } }, "seconds": 1.6458606719970703}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c40", "split": "test", "n": 1000, "nfe": 12, "seed": 0, "board_accuracy": 1.0, "clues_min": 40, "clues_max": 40, "clues_mean": 40.0, "by_clue": { "40": { "n": 1000, "board": 1000 } }, "seconds": 14.669137954711914}123456789101112131415161718192021{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_c40", "split": "test", "n": 1000, "nfe": 61, "seed": 0, "board_accuracy": 1.0, "clues_min": 40, "clues_max": 40, "clues_mean": 40.0, "by_clue": { "40": { "n": 1000, "board": 1000 } }, "seconds": 49.23768758773804}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_hard", "split": "test", "n": 1000, "nfe": 1, "seed": 0, "board_accuracy": 0.973, "clues_min": 21, "clues_max": 28, "clues_mean": 24.318, "by_clue": { "21": { "n": 3, "board": 3 }, "22": { "n": 43, "board": 40 }, "23": { "n": 181, "board": 176 }, "24": { "n": 345, "board": 337 }, "25": { "n": 282, "board": 276 }, "26": { "n": 127, "board": 123 }, "27": { "n": 18, "board": 17 }, "28": { "n": 1, "board": 1 } }, "seconds": 1.6644773483276367}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "model": "ours, recurrent", "params": "212k", "run": "/home/ubuntu/w/runs/rec1-full-s0", "data": "/home/ubuntu/w/data/sudoku_hard", "split": "test", "n": 1000, "nfe": 12, "seed": 0, "board_accuracy": 0.989, "clues_min": 21, "clues_max": 28, "clues_mean": 24.318, "by_clue": { "21": { "n": 3, "board": 3 }, "22": { "n": 43, "board": 42 }, "23": { "n": 181, "board": 178 }, "24": { "n": 345, "board": 342 }, "25": { "n": 282, "board": 281 }, "26": { "n": 127, "board": 124 }, "27": { "n": 18, "board": 18 }, "28": { "n": 1, "board": 1 } }, "seconds": 14.832441091537476}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "model": "ours, recurrent", "params": "212k", "run": "runs/rec1-full-s0", "data": "data/sudoku_hard", "split": "test", "n": 1000, "nfe": 61, "seed": 0, "board_accuracy": 0.997, "clues_min": 21, "clues_max": 28, "clues_mean": 24.318, "by_clue": { "21": { "n": 3, "board": 3 }, "22": { "n": 43, "board": 42 }, "23": { "n": 181, "board": 181 }, "24": { "n": 345, "board": 344 }, "25": { "n": 282, "board": 282 }, "26": { "n": 127, "board": 126 }, "27": { "n": 18, "board": 18 }, "28": { "n": 1, "board": 1 } }, "seconds": 78.46456527709961}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Training and inference FLOPs for our recurrent model and for NCM, measured.
Counts with torch.utils.flop_counter.FlopCounterMode on the real models and thereal training/decoding code paths, so the compute comparison in the README is ameasurement rather than a parameter-count estimate.
python ncm/count_flops.py --upstream /path/to/HazyResearch-ncm \ --ours runs/rec1-full-s0 --ncm-config runs/ncm-same-data-s0/config.yaml \ --data data/sudoku_hard --out ncm/results/compute_flops.json"""import argparseimport jsonimport sysfrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Ffrom torch.utils.flop_counter import FlopCounterMode
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE.parent / 'src'))sys.path.insert(0, str(HERE))
def flops(fn): with FlopCounterMode(display=False) as fc: fn() return fc.get_total_flops()
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--upstream', type=Path, required=True) ap.add_argument('--ours', type=Path, required=True) ap.add_argument('--ncm-config', type=Path, required=True) ap.add_argument('--data', type=Path, required=True) ap.add_argument('--out', type=Path, required=True) ap.add_argument('--device', default='cuda') a = ap.parse_args() dev = a.device sys.path.insert(0, str(a.upstream.resolve())) import diffusion as dfn from eval_ours import load_ours from omegaconf import OmegaConf from models.vqvae import VQVAE from models.next_concept import NextConceptTransformer from train_same_data import generator_batch, grid_tokens
Ptr = torch.from_numpy(np.load(a.data / 'train_puz.npy')[:256]).long().to(dev) Str = torch.from_numpy(np.load(a.data / 'train_sol.npy')[:256]).long().to(dev) Pte = torch.from_numpy(np.load(a.data / 'test_puz.npy')[:1]).long().to(dev) Ste = torch.from_numpy(np.load(a.data / 'test_sol.npy')[:1]).long().to(dev) out = {'counter': 'torch.utils.flop_counter.FlopCounterMode', 'batch': 256}
# ---- ours: one training step at R=32, inference at R=64 for K passes model, tok, cfg = load_ours(str(a.ours), dev) model.train() model.recurrences = 32 model.zero_grad(set_to_none=True) out['ours_train_step'] = flops(lambda: dfn.recurrent_cond_loss( model, Str - 1, Ptr == 0, tok, 'full', 8, 1.0, deep_sup=True).backward()) out['ours_train_steps'] = 120000 model.eval() model.recurrences = 64 bl = Pte == 0 x = torch.where(bl, torch.full_like(Ste, tok.mask), Ste - 1) with torch.no_grad(): out['ours_infer_per_puzzle'] = {str(K): flops(lambda: dfn.fixed_k_decode( model, x, tok, dev, K, fillable=bl)) for K in (1, 12, 61)} out['ours_params'] = sum(p.numel() for p in model.parameters()) del model torch.cuda.empty_cache()
# ---- NCM: tokenizer and generator steps (micro-batch 64 x 4 = global 256) cfgn = OmegaConf.load(a.ncm_config) codec = VQVAE(**cfgn.tokenizer.vqvae).to(dev).train() P, S = Ptr[:64], Str[:64]
def tok_step(): with torch.autocast('cuda', dtype=torch.bfloat16, enabled=dev == 'cuda'): t = grid_tokens(S) logits, vq, *_ = codec(t) (F.cross_entropy(logits.float().reshape(-1, 12), t.reshape(-1)) + vq).backward() out['ncm_tokenizer_step'] = 4 * flops(tok_step) codec.eval().requires_grad_(False) gen = NextConceptTransformer(codec, cfgn.model).to(dev).train()
def gen_step(): with torch.autocast('cuda', dtype=torch.bfloat16, enabled=dev == 'cuda'): inp, tgt = generator_batch(codec, gen, P, S) F.cross_entropy(gen(inp).float().reshape(-1, 16), tgt.reshape(-1)).backward() out['ncm_generator_step'] = 4 * flops(gen_step) gen.eval().requires_grad_(False)
def infer(): _, latent = gen.generate(None, grid_tokens(Pte, prefix=True), temperature=0., top_k=0, top_p=1., soft_decisions=True, soft_temperature=3.75, return_latent=True, use_kv_cache=True) codec.decoder(latent) with torch.no_grad(): out['ncm_infer_per_puzzle'] = flops(infer) out['ncm_params'] = {'generator': sum(p.numel() for p in gen.parameters()), 'codec': sum(p.numel() for p in codec.parameters())}
E = 1e18 out['training_total_eflop'] = { 'ours_rec1_full_120k': out['ours_train_step'] * 120000 / E, 'ncm_our_data_22405': (out['ncm_tokenizer_step'] * 1e4 + out['ncm_generator_step'] * 22405) / E, 'ncm_our_data_50000': (out['ncm_tokenizer_step'] * 1e4 + out['ncm_generator_step'] * 5e4) / E, 'ncm_paper_budget_batch1024': 4 * (out['ncm_tokenizer_step'] * 1e4 + out['ncm_generator_step'] * 5e4) / E, } a.out.parent.mkdir(parents=True, exist_ok=True) a.out.write_text(json.dumps(out, indent=2)) print(json.dumps(out, indent=2))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""Score a finished `train_same_data.py` run on another test set.
Rebuilds the codec and generator from the run's `config.yaml`, `tokenizer.pt`and `generator.pt`, then applies the trainer's own `evaluate` (same decodingsettings, same metrics) to `<data>/test_puz.npy` and `<data>/test_sol.npy`.
python ncm/eval_same_data.py --upstream /path/to/HazyResearch-ncm \ --run runs/ncm-same-data-s0-resumed --data data/sudoku_c30 \ --out ncm/results/ncm_same_data_c30.json"""import argparseimport jsonimport sysfrom pathlib import Path
import torchfrom omegaconf import OmegaConf
sys.path.insert(0, str(Path(__file__).resolve().parent))from train_same_data import evaluate # noqa: E402
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--upstream', type=Path, required=True) ap.add_argument('--run', type=Path, required=True) ap.add_argument('--data', type=Path, required=True) ap.add_argument('--out', type=Path, required=True) ap.add_argument('--batch', type=int, default=64) ap.add_argument('--device', default='cuda') a = ap.parse_args() sys.path.insert(0, str(a.upstream.resolve())) from models.vqvae import VQVAE from models.next_concept import NextConceptTransformer config = OmegaConf.load(a.run / 'config.yaml') codec = VQVAE(**config.tokenizer.vqvae).to(a.device) codec.load_state_dict(torch.load(a.run / 'tokenizer.pt', map_location=a.device, weights_only=False)['model']) codec.eval().requires_grad_(False) gen = NextConceptTransformer(codec, config.model).to(a.device) ck = torch.load(a.run / 'generator.pt', map_location=a.device, weights_only=False) gen.load_state_dict(ck['model']) result = evaluate(codec, gen, a.data, a.batch, a.device) result.pop('predictions') result.update({'run': a.run.name, 'generator_step': ck['step'], 'test_set': a.data.name}) a.out.parent.mkdir(parents=True, exist_ok=True) a.out.write_text(json.dumps(result, indent=2)) print(json.dumps(result), flush=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Build test sets at a fixed clue count, for a like-for-like comparison.
Our own benchmark is made of *minimal* puzzles, so its clue count is whateverminimality happens to leave (21-28, mean 24.3). The NCM paper instead definesdifficulty by a fixed clue count: 40 easy, 35 medium, 30 hard. Comparing amodel trained at 30 clues against a test set at 24 confounds architecture withdistribution shift, so this script generates sets at their clue counts usingthe same solution sampler and the same uniqueness guarantee as our generator.
The difference from `src/gen_hard_sudoku.py` is only the stopping rule: cellsare removed until the target clue count is reached rather than until nothingmore can be removed. Uniqueness is still re-verified after every removal, soboard accuracy stays well defined.
python ncm/make_clue_sets.py --clues 30 --n 1000 --out data/sudoku_c30
Pass --train_sol to assert the new set shares no solution with our trainingsplit, including under digit relabelling."""import argparseimport osimport sysimport timefrom functools import partialfrom multiprocessing import Poolfrom pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))from gen_hard_sudoku import CELLS, canon, count_solutions, random_solution # noqa: E402from gen_hard_sudoku import make_one as make_minimal # noqa: E402
def make_one(seed, clues): """One puzzle with exactly `clues` givens, unique at every step.
Returns (puzzle, solution) or None if this grid could not be thinned that far while staying unique, which the caller retries with another seed. """ rng = np.random.default_rng(seed) sol = random_solution(rng) g = sol.copy() order = rng.permutation(CELLS) remaining = CELLS
for i in order: if remaining <= clues: break keep = g[i] g[i] = 0 if count_solutions(g, 2) == 1: remaining -= 1 else: g[i] = keep
return (g, sol) if remaining == clues else None
def main(): ap = argparse.ArgumentParser() ap.add_argument("--clues", type=int, default=0, help="givens per puzzle, e.g. 30") ap.add_argument("--minimal", action="store_true", help="generate minimal puzzles instead, as the project's own test set is " "built; clue count then falls where it falls and is reported") ap.add_argument("--n", type=int, default=1000, help="puzzles to produce") ap.add_argument("--out", required=True) ap.add_argument("--split", default="test", help="file prefix, e.g. test -> test_puz.npy") ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1)) ap.add_argument("--seed0", type=int, default=0, help="first worker seed. 0 means 1,000,000 x clues: src/gen_hard_sudoku.py " "drew the training and test splits from seeds 0..100,999 with the same " "solution sampler, so low seeds regenerate training solutions exactly") ap.add_argument("--train_sol", default="", help="training solutions to check against") a = ap.parse_args()
if a.minimal == bool(a.clues): raise SystemExit("pass either --clues N or --minimal, not both and not neither") if a.clues and not 17 <= a.clues <= 60: raise SystemExit("--clues outside the sensible range 17-60")
if a.seed0 == 0: a.seed0 = 1_000_000 * (a.clues or 1) worker = make_minimal if a.minimal else partial(make_one, clues=a.clues)
t0 = time.time() got, seed, batch = [], a.seed0, max(a.n, 64) with Pool(a.workers) as pool: while len(got) < a.n: seeds = range(seed, seed + batch) seed += batch for r in pool.map(worker, seeds, chunksize=4): if r is not None: got.append(r) print(f" {len(got)}/{a.n} after {time.time() - t0:.0f}s", flush=True)
got = got[:a.n] P = np.stack([g for g, _ in got]).astype(np.uint8) S = np.stack([s for _, s in got]).astype(np.uint8)
counts = (P > 0).sum(1) if a.minimal: hist = {int(c): int((counts == c).sum()) for c in sorted(set(counts))} print(f"clues: min={counts.min()} max={counts.max()} mean={counts.mean():.1f} {hist}") else: assert counts.min() == counts.max() == a.clues, f"clue counts drifted: {sorted(set(counts))}"
# every puzzle must still admit exactly one solution bad = sum(count_solutions(P[i], 2) != 1 for i in range(0, len(P), 25)) assert bad == 0, f"{bad} sampled puzzles are not unique"
# the solutions themselves must be distinct, up to digit relabelling canon_sols = {canon(s) for s in S} print(f"distinct solutions up to relabelling: {len(canon_sols)}/{len(S)}")
if a.train_sol: tr = {canon(s) for s in np.load(a.train_sol)} leak = sum(canon(s) in tr for s in S) print(f"solutions also in training (up to relabelling): {leak}") assert leak == 0, "leakage against the training split"
os.makedirs(a.out, exist_ok=True) np.save(os.path.join(a.out, f"{a.split}_puz.npy"), P) np.save(os.path.join(a.out, f"{a.split}_sol.npy"), S) print(f"saved {P.shape} puzzles to {a.out} in {time.time() - t0:.0f}s")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378"""Budget-limited, from-scratch NCM reimplementation using the official modules.
Both stages see only train_*.npy. Test data are opened once, after training.This supplies a training loop absent from the upstream inference release; it isnot a reproduction of the authors' original training implementation or budget."""import argparseimport shutilimport csvimport hashlibimport jsonimport mathfrom pathlib import Pathimport randomimport subprocessimport sysimport time
import numpy as npimport torchimport torch.nn.functional as Ffrom omegaconf import OmegaConf
def write_json(path, data): path = Path(path) tmp = path.with_suffix(path.suffix + '.tmp') tmp.write_text(json.dumps(data, indent=2) + '\n') tmp.replace(path)
def sha256(path): h = hashlib.sha256() with open(path, 'rb') as f: for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block) return h.hexdigest()
def grid_tokens(cells, prefix=False): """Fixed positions retain malformed generated separators as errors at eval.""" cells = cells.reshape(-1, 9, 9) sep = torch.full((len(cells), 9, 1), 10, dtype=cells.dtype, device=cells.device) body = torch.cat([cells, sep], -1).reshape(len(cells), 90)[:, :89] if not prefix: return body edge = torch.full((len(cells), 1), 11, dtype=cells.dtype, device=cells.device) return torch.cat([edge, body, edge], 1)
def relabel(puzzles, solutions): """Same paired digit-permutation augmentation as the recurrent baseline.""" table = torch.cat([torch.zeros(1, dtype=torch.long, device=solutions.device), torch.randperm(9, device=solutions.device) + 1]) return table[puzzles], table[solutions]
def generator_batch(codec, model, puzzles, solutions): """Each level sees ONLY the reconstruction of earlier solution codes.""" with torch.no_grad(): codes = codec.encode(grid_tokens(solutions)) previous = codec.vq.idx_to_ncm_input(codes) prefix = codec.encoder.wte(grid_tokens(puzzles, prefix=True)) # Keep this outside no_grad so the learned level-zero query receives gradients. inputs = torch.cat([prefix, model.build_l0_query_input(len(puzzles)), previous], 1) return inputs, codes
def learning_rate(step, total, peak, warmup): if step < warmup: return peak * (step + 1) / warmup progress = min(1., (step - warmup) / max(1, total - warmup)) return peak * (0.1 + 0.9 * .5 * (1 + math.cos(math.pi * progress)))
def plot_logs(out): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 2, figsize=(11, 4)) for ax, stage in zip(axes, ['tokenizer', 'generator']): path = out / (stage + '_training.csv') if path.exists(): with path.open() as f: rows = list(csv.DictReader(f)) ax.plot([int(r['step']) for r in rows], [float(r['loss']) for r in rows]) ax.set(title=stage.capitalize() + ' training loss', xlabel='Optimizer updates', ylabel='Loss') ax.grid(alpha=.2) fig.suptitle('NCM from scratch on our training split (single seed, budget constrained)') fig.tight_layout() fig.savefig(out / 'training_curves.png', dpi=160) plt.close(fig)
def sync_hf(out, repo, prefix): """Upload only this run's artifacts; the API key is never inside out.""" if not repo: return from huggingface_hub import HfApi plot_logs(out) HfApi().upload_folder(repo_id=repo, folder_path=str(out), path_in_repo=prefix, ignore_patterns=['*.tmp', '__pycache__/*'], commit_message='NCM same-data training progress and artifacts')
def save_checkpoint(path, model, opt, step): tmp = path.with_suffix('.tmp') torch.save({'model': model.state_dict(), 'optimizer': opt.state_dict(), 'step': step, 'torch_rng': torch.get_rng_state(), 'cuda_rng': torch.cuda.get_rng_state_all(), 'numpy_rng': np.random.get_state(), 'python_rng': random.getstate()}, tmp) tmp.replace(path)
def evaluate(codec, model, data, batch, device): # This is the only function opening the held-out test files. puzzles = np.load(data / 'test_puz.npy', allow_pickle=False).reshape(-1, 81) solutions = np.load(data / 'test_sol.npy', allow_pickle=False).reshape(-1, 81) if puzzles.shape != solutions.shape: raise ValueError('Test puzzle and solution shapes differ') from ncm_encoding import is_legal codec.eval() model.eval() outcomes = [] positions = torch.tensor([r * 10 + c for r in range(9) for c in range(9)], device=device) with torch.inference_mode(): for i in range(0, len(puzzles), batch): p = torch.tensor(puzzles[i:i+batch], dtype=torch.long, device=device) with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device == 'cuda'): _, latent = model.generate(None, grid_tokens(p, prefix=True), temperature=0., top_k=0, top_p=1., soft_decisions=True, soft_temperature=3.75, return_latent=True, use_kv_cache=True) raw = codec.decoder(latent).argmax(-1) cells = raw[:, positions].cpu().numpy() raw_np = raw.cpu().numpy() for j, row in enumerate(cells): ref = solutions[i+j] puz = puzzles[i+j] separators_ok = bool((raw_np[j, [9,19,29,39,49,59,69,79]] == 10).all()) outcomes.append({'index': i+j, 'board': bool((row == ref).all()), 'legal': is_legal(row), 'clues': bool(((puz == 0) | (row == puz)).all()), 'separators': separators_ok, 'cells': row.tolist()}) print('Evaluation', min(i+batch, len(puzzles)), '/', len(puzzles), flush=True) return {'n': len(outcomes), 'nfe': len(codec.vq.levels), 'board_accuracy': float(np.mean([r['board'] for r in outcomes])), 'legal_rate': float(np.mean([r['legal'] for r in outcomes])), 'clue_consistent_rate': float(np.mean([r['clues'] for r in outcomes])), 'separator_correct_rate': float(np.mean([r['separators'] for r in outcomes])), 'predictions': outcomes}
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--upstream', type=Path, required=True) ap.add_argument('--data', type=Path, required=True) ap.add_argument('--out', type=Path, required=True) ap.add_argument('--seed', type=int, default=0) ap.add_argument('--tokenizer-steps', type=int, default=10000) ap.add_argument('--generator-steps', type=int, default=50000) ap.add_argument('--batch', type=int, default=256) ap.add_argument('--micro-batch', type=int, default=64) ap.add_argument('--tokenizer-max-seconds', type=float, default=1800) ap.add_argument('--train-until', type=float, required=True, help='Absolute epoch deadline') ap.add_argument('--hf-repo', default='') ap.add_argument('--hf-prefix', default='Fixes/ncm-same-data-s0') ap.add_argument('--device', default='cuda') ap.add_argument('--smoke', action='store_true', help='Two optimizer updates per stage on TRAIN ONLY') ap.add_argument('--resume-from', type=Path, default=None, help='Finished run directory (tokenizer.pt, generator_resume.pt, logs, manifest). ' 'Reuses its trained tokenizer and continues the generator from its last ' 'checkpoint on the same LR schedule; batch must match.') a = ap.parse_args() if a.batch % a.micro_batch or a.micro_batch < 1: ap.error('--batch must be a positive multiple of --micro-batch') if a.out.exists() and (a.out / 'manifest.json').exists(): ap.error('Use a fresh output directory; existing checkpoints will not be overwritten') a.out.mkdir(parents=True, exist_ok=True) sys.path.insert(0, str(a.upstream.resolve())) from models.vqvae import VQVAE from models.next_concept import NextConceptTransformer torch.set_num_threads(8) torch.manual_seed(a.seed) np.random.seed(a.seed) random.seed(a.seed) if a.device == 'cuda': torch.cuda.manual_seed_all(a.seed) torch.backends.cuda.matmul.allow_tf32 = True config = OmegaConf.load(a.upstream / 'config/eval/sudoku-hard.yaml') OmegaConf.save(config, a.out / 'config.yaml') puz = np.load(a.data / 'train_puz.npy', allow_pickle=False).reshape(-1, 81) sol = np.load(a.data / 'train_sol.npy', allow_pickle=False).reshape(-1, 81) if puz.shape != sol.shape or not ((puz >= 0) & (puz <= 9)).all() or not ((sol >= 1) & (sol <= 9)).all(): raise ValueError('Malformed training arrays') if not ((puz == 0) | (puz == sol)).all(): raise ValueError('Training clues disagree with solutions') manifest = {'experiment': 'NCM trained from scratch on our exact training split', 'initialization': 'random for both codec and generator; no pretrained weights', 'upstream_commit': subprocess.check_output(['git', '-C', str(a.upstream), 'rev-parse', 'HEAD'], text=True).strip(), 'train_examples': len(puz), 'train_sha256': {name: sha256(a.data / name) for name in ['train_puz.npy', 'train_sol.npy']}, 'seed': a.seed, 'args': {k:str(v) if isinstance(v,Path) else v for k,v in vars(a).items()}, 'paper_budget': {'tokenizer_steps':10000,'generator_steps':50000,'global_batch':1024}, 'limitations': ['Our training loop around the official inference modules, not the original trainer.', 'Global batch 256 rather than published 1024; single seed; hard wall-clock limit.', 'Training time and parameter count are not matched to the recurrent baseline.', 'Training-only diagnostics; test data used once after final checkpoint.'], 'status': 'training', 'started_at_epoch': time.time()} write_json(a.out / 'manifest.json', manifest) train_p = torch.tensor(puz, dtype=torch.long, device=a.device) train_s = torch.tensor(sol, dtype=torch.long, device=a.device) codec = VQVAE(**config.tokenizer.vqvae).to(a.device) accum = a.batch // a.micro_batch # EMA updates happen per microbatch; adjust decay to preserve a per-update 0.99. codec.vq.base_decay = .99 ** (1 / accum) models = {} resume = None if a.resume_from is not None: prev = json.loads((a.resume_from / 'manifest.json').read_text()) if prev['generator']['global_batch'] != a.batch or prev['generator']['steps_planned'] != a.generator_steps: raise ValueError('Resume must keep the same global batch and planned generator steps') if prev['train_sha256'] != manifest['train_sha256']: raise ValueError('Training arrays differ from the run being resumed') resume = torch.load(a.resume_from / 'generator_resume.pt', map_location=a.device, weights_only=False) codec.load_state_dict(torch.load(a.resume_from / 'tokenizer.pt', map_location=a.device, weights_only=False)['model']) for name in ['tokenizer.pt', 'tokenizer_training.csv']: shutil.copy(a.resume_from / name, a.out / name) manifest['tokenizer'] = prev['tokenizer'] manifest['tokenizer_train_reconstruction'] = prev.get('tokenizer_train_reconstruction') manifest['resumed_from'] = {'run': str(a.resume_from.name), 'generator_step': resume['step'], 'previous_generator_seconds': prev['generator']['seconds'], 'note': 'Tokenizer reused unchanged; generator model, optimizer and RNG state restored.'} write_json(a.out / 'manifest.json', manifest) last_sync = time.time() start = time.time() for stage in ['tokenizer', 'generator']: if stage == 'tokenizer' and resume is not None: codec.eval() continue if stage == 'tokenizer': model = codec.train() total, peak, warmup = a.tokenizer_steps, 5e-4, 500 deadline = min(a.train_until, time.time() + a.tokenizer_max_seconds) else: codec.eval().requires_grad_(False) model = NextConceptTransformer(codec, config.model).to(a.device).train() total, peak, warmup = a.generator_steps, 3e-4, 1000 deadline = a.train_until if a.smoke: total, warmup = 2, 1 opt = torch.optim.AdamW(model.parameters(), lr=peak, betas=(.9,.99), weight_decay=.01) start_step, prior_seconds = 0, 0. logpath = a.out / (stage + '_training.csv') if stage == 'generator' and resume is not None: model.load_state_dict(resume['model']) opt.load_state_dict(resume['optimizer']) start_step = resume['step'] prior_seconds = manifest['resumed_from']['previous_generator_seconds'] torch.set_rng_state(resume['torch_rng'].cpu()) if a.device == 'cuda': torch.cuda.set_rng_state_all([t.cpu() for t in resume['cuda_rng']]) np.random.set_state(resume['numpy_rng']) random.setstate(resume['python_rng']) shutil.copy(a.resume_from / 'generator_training.csv', logpath) print('resumed generator at step', start_step, flush=True) completed = start_step stage_start = time.time() - prior_seconds with logpath.open('a' if start_step else 'w', buffering=1) as logfile: writer = csv.DictWriter(logfile, fieldnames=['step','loss','lr','elapsed_seconds','examples_seen']) if not start_step: writer.writeheader() for step in range(start_step, total): if time.time() >= deadline: break opt.zero_grad(set_to_none=True) lr = learning_rate(step, total, peak, min(warmup,total)) for group in opt.param_groups: group['lr'] = lr loss_total = 0. for _ in range(accum): idx = torch.randint(len(train_s), (a.micro_batch,), device=a.device) p, s = relabel(train_p[idx], train_s[idx]) with torch.autocast('cuda', dtype=torch.bfloat16, enabled=a.device == 'cuda'): if stage == 'tokenizer': target = grid_tokens(s) logits, vqloss, *_ = codec(target) loss = F.cross_entropy(logits.float().reshape(-1,12), target.reshape(-1)) + vqloss else: inputs, target = generator_batch(codec, model, p, s) logits = model(inputs) if logits.shape[:2] != target.shape: raise ValueError('Generator output and all-level targets differ') loss = F.cross_entropy(logits.float().reshape(-1,16), target.reshape(-1)) if not torch.isfinite(loss): raise FloatingPointError(f'Nonfinite {stage} loss at step {step}') (loss / accum).backward() loss_total += loss.detach().item() / accum torch.nn.utils.clip_grad_norm_(model.parameters(), 1.) if stage == 'generator' and step == 0 and model.l0_queries.grad is None: raise RuntimeError('Level-zero query received no gradient') opt.step() completed = step + 1 if completed % 10 == 0 or completed == 1 or completed == total: row = {'step':completed,'loss':loss_total,'lr':lr,'elapsed_seconds':time.time()-stage_start,'examples_seen':completed*a.batch} writer.writerow(row) if completed % 100 == 0 or completed == 1: print(stage, completed, '/', total, 'loss', round(loss_total,5), 'seconds', round(time.time()-stage_start), flush=True) if completed % 1000 == 0: save_checkpoint(a.out / (stage + '_resume.pt'), model, opt, completed) plot_logs(a.out) if not a.smoke and time.time()-last_sync > 900: save_checkpoint(a.out / (stage + '_resume.pt'), model, opt, completed) try: sync_hf(a.out, a.hf_repo, a.hf_prefix) except Exception as exc: print('Intermediate upload failed:', type(exc).__name__, flush=True) last_sync = time.time() if completed == 0: raise RuntimeError(f'No time remained to train {stage}; cannot report an untrained baseline') save_checkpoint(a.out / (stage + '_resume.pt'), model, opt, completed) final_tmp = a.out / (stage + '_final.tmp') torch.save({'model': model.state_dict(), 'step':completed}, final_tmp) final_tmp.replace(a.out / (stage+'.pt')) manifest[stage] = {'steps_completed':completed,'steps_planned':total,'global_batch':a.batch, 'examples_seen':completed*a.batch,'seconds':time.time()-stage_start, 'parameters':sum(p.numel() for p in model.parameters()),'budget_limited':completed<total} write_json(a.out / 'manifest.json', manifest) models[stage] = model print(stage, 'saved', manifest[stage], flush=True) if stage == 'tokenizer': codec.eval() with torch.inference_mode(): target = grid_tokens(train_s[:128]) pred = codec.decode(codec.encode(target)).argmax(-1) manifest['tokenizer_train_reconstruction'] = {'n':len(target), 'token_accuracy':(pred==target).float().mean().item(), 'exact_sequence_accuracy':(pred==target).all(1).float().mean().item()} if not a.smoke: try: sync_hf(a.out, a.hf_repo, a.hf_prefix) except Exception as exc: print('Stage upload failed:', type(exc).__name__, flush=True) manifest['status'] = 'smoke_passed' if a.smoke else 'evaluating_final_checkpoint' manifest['training_seconds'] = time.time()-start write_json(a.out / 'manifest.json', manifest) if a.smoke: # Verify conditional generation and absence of future-code leakage on TRAIN. model = models['generator'].eval() with torch.inference_mode(): p, s = train_p[:2], train_s[:2] x1, _ = generator_batch(codec, model, p, s) x2, _ = generator_batch(codec, model, p, train_s[2:4]) y1, y2 = model(x1), model(x2) torch.testing.assert_close(y1[:, :1], y2[:, :1], rtol=0, atol=1e-5) codes, latent = model.generate(None, grid_tokens(p, prefix=True), temperature=0., top_k=0, top_p=1., return_latent=True, soft_decisions=True, soft_temperature=3.75) assert codes.shape == (2, sum(codec.vq.levels)) assert codec.decoder(latent).shape == (2, 89, 12) manifest['smoke_checks'] = ['Both stages backpropagated finite losses', 'Learned level-zero queries received gradients', 'Level-zero predictions independent of future solution codes', 'Conditional generation and codec decoding have expected shapes', 'No test arrays loaded'] else: result = evaluate(codec, models['generator'], a.data, min(64,a.micro_batch), a.device) predictions = result.pop('predictions') write_json(a.out / 'test_predictions.json', predictions) result.update({'seed':a.seed,'training':{k:manifest[k] for k in ['tokenizer','generator']}, 'comparison_caveat':'Same training/test split; differing architecture, training compute, and training loop.'}) write_json(a.out / 'result.json', result) manifest['status'] = 'smoke_passed' if a.smoke else 'complete_budget_constrained_run' manifest['finished_at_epoch'] = time.time() write_json(a.out / 'manifest.json', manifest) plot_logs(a.out) sync_hf(a.out, a.hf_repo, a.hf_prefix) print(manifest['status'], flush=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319"""Masked diffusion on Sudoku: does committing by certainty solve constraints?
The benchmark is SATNet's 9x9 Sudoku (Wang et al., ICML 2019) with itsconventional 9,000 / 1,000 split, scored by BOARD-level accuracy - all 81 cellscorrect - which is the metric the published numbers use.
The claim under test is specific. Sudoku has a unique answer, so there is noinformation-theoretic obstacle whatsoever: every cell's true conditional is apoint mass and TC is zero. The entire difficulty is therefore mode (i), plus theORDER in which cells are committed. A decoder that commits the lowest-entropycells first, recomputes, and repeats is doing classical constraint propagation -fill the forced cells, propagate, repeat - without being told to. A fixed-Kdecoder that commits a fixed fraction per pass regardless of certainty is not.
Prediction, registered before the runs: entropy-budgeted decoding should beatfixed-K decoding by a very large margin here, larger than anywhere else in thisproject, because Sudoku is the case where commit ORDER carries almost all of theinformation. Confidence-thresholding is included as the published competitor."""import argparse, json, math, os, timeimport numpy as npimport torch
from model import RecurrentDenoiser, Transformerimport diffusion as dfnfrom sudoku import (CELLS, SudokuTokenizer, board_accuracy, cell_accuracy, consistent_with_clues, is_valid_solution, load_satnet, split)
def get_args(): p = argparse.ArgumentParser() p.add_argument("--mode", choices=["mdlm", "matched", "full"], default="mdlm") p.add_argument("--all_cells", action="store_true", help="direct objective: supervise all 81 cells, not only the " "blanks. Denser signal - the model must also reproduce " "the given clues - which is how the published recurrent " "classifier is trained and the most likely reason our " "first attempt plateaued at loss 0.34 against 0.15") p.add_argument("--objective", choices=["diffusion", "direct", "ar"], default="diffusion", help="diffusion = mask at a random ratio and denoise; " "direct = predict every blank from the puzzle with no " "masking schedule, which is the Recurrent Transformer " "setup and the baseline that asks whether the diffusion " "framing earns its place; " "ar = autoregressive, blanks filled left to right") p.add_argument("--K", type=int, default=8) p.add_argument("--lam", type=float, default=1.0) p.add_argument("--pe", default="ape", choices=["ape", "rope", "sin"]) p.add_argument("--recurrent", action="store_true", help="weight-shared block applied R times with deep supervision") p.add_argument("--R", type=int, default=32, help="training recurrences") p.add_argument("--step_embed", action="store_true", help="condition each loop on its index, as R-MDM does. Needed " "for a faithful reproduction of their architecture") p.add_argument("--no_inject", action="store_true", help="ablation: drop input injection, keeping architecture and " "depth identical. Isolates weight sharing from injection, " "which the 32-layer comparison conflates") p.add_argument("--no_deep_sup", action="store_true", help="ablation: supervise only the final recurrence") p.add_argument("--R_infer", type=int, default=0, help="inference recurrences (0 = same as training)") p.add_argument("--root", default="data/sudoku") p.add_argument("--hard", default="", help="directory of the generated HARD benchmark (npy files); " "overrides --root. Minimal puzzles at ~24 clues, where " "constraint propagation alone solves about 4%") p.add_argument("--augment", action="store_true", help="relabel digits by a random permutation (a Sudoku symmetry)") p.add_argument("--d", type=int, default=512) p.add_argument("--layers", type=int, default=10) p.add_argument("--heads", type=int, default=8) p.add_argument("--bs", type=int, default=128) p.add_argument("--steps", type=int, default=80000) p.add_argument("--lr", type=float, default=1e-4) p.add_argument("--warmup", type=int, default=2000) p.add_argument("--seed", type=int, default=0) p.add_argument("--eval_bs", type=int, default=200) p.add_argument("--ckpt_every", type=int, default=4000, help="steps between checkpoints; 0 disables") p.add_argument("--out", default="runs/sud") p.add_argument("--skip_final_eval", action="store_true", help="save model.pt + result.json (args only) and exit; score separately " "with ncm/eval_ours.py. The full sweep is ~570 passes per puzzle, " "hours on an 18k-puzzle test set such as RRN") return p.parse_args()
a = get_args()torch.manual_seed(a.seed); np.random.seed(a.seed)dev = "cuda" if torch.cuda.is_available() else "cpu"os.makedirs(a.out, exist_ok=True)
if a.hard: # the generated benchmark: minimal puzzles, uniqueness verified per removal, # train/test solutions disjoint even up to digit relabelling Xtr = np.load(os.path.join(a.hard, "train_puz.npy")) Ytr = np.load(os.path.join(a.hard, "train_sol.npy")) Xte = np.load(os.path.join(a.hard, "test_puz.npy")) Yte = np.load(os.path.join(a.hard, "test_sol.npy")) tok = SudokuTokenizer() print(f"HARD sudoku: train {Xtr.shape} test {Xte.shape} " f"clues mean {(Xtr>0).sum(1).mean():.1f} " f"(min {(Xtr>0).sum(1).min()} max {(Xtr>0).sum(1).max()})", flush=True)else: X, Y, tok = load_satnet(a.root) (Xtr, Ytr), (Xte, Yte) = split(X, Y) print(f"sudoku: train {Xtr.shape} test {Xte.shape} vocab {len(tok)} " f"clues/puzzle mean {(X>0).sum(1).mean():.1f}", flush=True)
# tokens are the SOLUTION digits shifted to 0-8; blanks are what gets maskedsol_tr = torch.from_numpy(Ytr - 1)blank_tr = torch.from_numpy(Xtr == 0)sol_te = torch.from_numpy(Yte - 1)blank_te = torch.from_numpy(Xte == 0)
if a.recurrent: model = RecurrentDenoiser(len(tok), a.d, a.layers, a.heads, a.pe, max_len=CELLS + 8, recurrences=a.R, inject=not a.no_inject, step_embed=a.step_embed).to(dev) print(f"params {model.n_params()/1e3:.0f}k RECURRENT R={a.R} " f"layers={a.layers} d={a.d} mode={a.mode} pe={a.pe}", flush=True)else: model = Transformer(len(tok), a.d, a.layers, a.heads, a.pe, causal=(a.objective == "ar"), max_len=(2 * CELLS + 8 if a.objective == "ar" else CELLS + 8)).to(dev) print(f"params {model.n_params()/1e6:.2f}M mode={a.mode} pe={a.pe}", flush=True)
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01)sched = torch.optim.lr_scheduler.LambdaLR( opt, lambda s: min(1.0, (s + 1) / a.warmup) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / a.steps))))
# ---- checkpoint / resume ---------------------------------------------------# The class allocation bills an H100 at 144/min against 9/min for a 5GB MIG# slice, so long runs belong on the cheap partition - which has shorter time# limits. Resuming from a checkpoint is what makes a long run survive being# split across several short jobs, and it costs no extra GPU-time: the# allocation charges GPU-seconds consumed, not jobs submitted.CKPT = os.path.join(a.out, "ckpt.pt")start_step = 0if os.path.exists(CKPT): st = torch.load(CKPT, map_location=dev) model.load_state_dict(st["model"]) opt.load_state_dict(st["opt"]) sched.load_state_dict(st["sched"]) start_step = st["step"] torch.set_rng_state(st["torch_rng"].cpu()) np.random.set_state(st["np_rng"]) print(f"resumed from {CKPT} at step {start_step}", flush=True)
def save_ckpt(step): tmp = CKPT + ".tmp" torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "sched": sched.state_dict(), "step": step, "torch_rng": torch.get_rng_state(), "np_rng": np.random.get_state()}, tmp) os.replace(tmp, CKPT) # atomic: a job killed mid-write leaves the old one
rng = np.random.default_rng(a.seed)t0 = time.time()for step in range(start_step, a.steps): idx = torch.randint(0, len(sol_tr), (a.bs,)) xb, ab = sol_tr[idx].clone(), blank_tr[idx] if a.augment: # relabelling the nine digits maps a valid grid to a valid grid, and # leaves the constraint structure - the thing being learned - untouched perm = torch.from_numpy(rng.permutation(9)) xb = perm[xb] xb, ab = xb.to(dev), ab.to(dev) opt.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(dev == "cuda")): if a.objective == "direct": # No masking schedule at all: the model always sees the real puzzle # and predicts every blank. This is what a recurrent classifier does, # and it is the control for whether diffusion adds anything. xin = torch.where(ab, torch.full_like(xb, tok.mask), xb) sup = torch.ones_like(ab) if a.all_cells else ab if a.recurrent: outs = model(xin, recurrences=None, return_all=True) if a.no_deep_sup: outs = outs[-1:] R = len(outs) loss, wsum = 0.0, 0.0 for r, lg in enumerate(outs): w = (r + 1) / R ce = torch.nn.functional.cross_entropy( lg.reshape(-1, lg.size(-1)), xb.reshape(-1), reduction="none").view(xb.shape) loss = loss + w * ((ce * sup).sum(1) / sup.sum(1).clamp_min(1)).mean() wsum += w loss = loss / wsum else: lg = model(xin) ce = torch.nn.functional.cross_entropy( lg.reshape(-1, lg.size(-1)), xb.reshape(-1), reduction="none").view(xb.shape) loss = ((ce * sup).sum(1) / sup.sum(1).clamp_min(1)).mean() elif a.objective == "ar": # Prefix-LM: [puzzle 81 tokens][solution 81 tokens], causal, loss on # the solution half only. Sudoku clues are scattered, so an in-place # causal model cannot see clues to its right; giving it the whole # puzzle as a prefix is the setup that actually makes AR competitive. puz = torch.where(ab, torch.full_like(xb, tok.mask), xb) seq = torch.cat([puz, xb], dim=1) # (B, 162) lg = model(seq) tgt = seq[:, 1:] lgt = lg[:, :-1] sup = torch.zeros_like(tgt, dtype=torch.bool) sup[:, CELLS - 1:] = True # solution half only ce = torch.nn.functional.cross_entropy( lgt.reshape(-1, lg.size(-1)), tgt.reshape(-1), reduction="none").view(tgt.shape) loss = ((ce * sup).sum(1) / sup.sum(1)).mean() elif a.recurrent: loss = dfn.recurrent_cond_loss(model, xb, ab, tok, a.mode, a.K, a.lam, deep_sup=not a.no_deep_sup) else: loss = dfn.pmd_loss(model, xb, ab, tok, a.mode, a.K, a.lam) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step(); sched.step() if step % 5000 == 0: print(f"step {step:6d} loss {loss.item():.4f} ({time.time()-t0:.0f}s)", flush=True) if a.ckpt_every and step and step % a.ckpt_every == 0: save_ckpt(step)save_ckpt(a.steps)
model.eval()if a.recurrent and a.R_infer: model.recurrences = a.R_infer print(f"inference recurrences set to {a.R_infer} (trained with {a.R})", flush=True)res = {"args": vars(a), "decode": {}}if a.skip_final_eval: torch.save(model.state_dict(), os.path.join(a.out, "model.pt")) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=2) print(f"saved to {a.out} (final evaluation skipped)", flush=True) raise SystemExit
@torch.no_grad()def evaluate(fn): """Board accuracy over the full test split, plus the diagnostics.""" preds, nfes = [], [] for i in range(0, len(sol_te), a.eval_bs): gold = sol_te[i:i + a.eval_bs].to(dev) bl = blank_te[i:i + a.eval_bs].to(dev) x = torch.where(bl, torch.full_like(gold, tok.mask), gold) y, nfe = fn(x, bl) preds.append(y.cpu()); nfes.append(nfe) P = torch.cat(preds).numpy() + 1 G = Yte board = board_accuracy(P, G) cell = cell_accuracy(P, G, Xte == 0) valid = float(np.mean([is_valid_solution(P[i]) for i in range(len(P))])) kept = float(np.mean([consistent_with_clues(P[i], Xte[i]) for i in range(len(P))])) return {"board": board, "cell": cell, "valid_sudoku": valid, "clues_kept": kept, "nfe": float(np.mean(nfes))}
def report(tag, key, r): res["decode"][key] = r print(f" {tag:<26}{r['nfe']:>7.1f}{r['board']*100:>10.2f}%{r['cell']*100:>9.2f}%" f"{r['valid_sudoku']*100:>9.2f}%", flush=True)
if a.objective == "ar": @torch.no_grad() def ar_decode(x, bl): """Generate the solution half token by token, conditioned on the puzzle.""" puz = x # already puzzle-with-masks seq = torch.cat([puz, torch.full_like(puz, tok.mask)], dim=1) for j in range(CELLS): pos = CELLS + j lg = model(seq[:, :pos])[:, -1] seq[:, pos] = lg.argmax(-1) return seq[:, CELLS:], CELLS report("autoregressive (L->R)", "ar", evaluate(ar_decode)) torch.save(model.state_dict(), os.path.join(a.out, "model.pt")) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=2) print(f"saved to {a.out}", flush=True) raise SystemExit
print("\n=== board accuracy against decoding budget ===", flush=True)print(f" {'rule':<26}{'NFE':>7}{'BOARD':>10}{'cell':>9}{'valid':>9}", flush=True)
print("fixed-K (commits a fixed share per pass, ignoring certainty):", flush=True)for K in (1, 2, 4, 8, 16, 32, 61): report(f"fixed-K K={K}", f"fixedK_{K}", evaluate(lambda x, bl, K=K: dfn.fixed_k_decode( model, x, tok, dev, K, fillable=bl)))
print("entropy-budget (= constraint propagation):", flush=True)for B in (0.01, 0.05, 0.2, 0.5, 1.0, 2.0): report(f"entropy-budget B={B}", f"entbudget_{B}", evaluate(lambda x, bl, B=B: dfn.entropy_budget_decode( model, x, tok, dev, B, max_steps=CELLS + 2, fillable=bl)))
print("confidence-threshold (published inference-time method):", flush=True)for tau in (0.9, 0.99, 0.999): report(f"confidence tau={tau}", f"conf_{tau}", evaluate(lambda x, bl, tau=tau: dfn.confidence_threshold_decode( model, x, tok, dev, tau, max_steps=CELLS + 2, fillable=bl)))
best = max(res["decode"].values(), key=lambda r: r["board"])res["best_board"] = best["board"]print(f"\nbest board accuracy: {best['board']*100:.2f}% at {best['nfe']:.1f} passes", flush=True)print(f"SATNet (Wang et al. ICML 2019) reports 98.3% board accuracy on this split.", flush=True)
torch.save(model.state_dict(), os.path.join(a.out, "model.pt"))json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=2)print(f"saved to {a.out}", flush=True)12345678910111213141516171819202122232425{ "counter": "torch.utils.flop_counter.FlopCounterMode", "batch": 256, "ours_train_step": 1740820709376, "ours_train_steps": 120000, "ours_infer_per_puzzle": { "1": 2266693632, "12": 27200323584, "61": 131468230656 }, "ours_params": 211968, "ncm_tokenizer_step": 355454025728, "ncm_generator_step": 18771248939008, "ncm_infer_per_puzzle": 22388792320, "ncm_params": { "generator": 25457600, "codec": 14896512 }, "training_total_eflop": { "ours_rec1_full_120k": 0.20889848512512, "ncm_our_data_22405": 0.42412437273575426, "ncm_our_data_50000": 0.94211698720768, "ncm_paper_budget_batch1024": 3.76846794883072 }}revision/README.mdAdded+84
revision/clue_sets/data/sudoku_c30/test_puz.npyAdded+3
revision/clue_sets/data/sudoku_c30/test_sol.npyAdded+3
revision/clue_sets/data/sudoku_c35/test_puz.npyAdded+3
revision/clue_sets/data/sudoku_c35/test_sol.npyAdded+3
revision/clue_sets/data/sudoku_c40/test_puz.npyAdded+3
revision/clue_sets/data/sudoku_c40/test_sol.npyAdded+3
revision/clue_sets/results/ncm_same_data_old_c30.jsonAdded+11
revision/clue_sets/results/ncm_same_data_old_c35.jsonAdded+11
revision/clue_sets/results/ncm_same_data_old_c40.jsonAdded+11
revision/clue_sets/results/ncm_same_data_old_hard.jsonAdded+11
revision/clue_sets/results/ncm_sudoku-easy_c40.jsonAdded+36
revision/clue_sets/results/ncm_sudoku-hard_c30.jsonAdded+36
revision/clue_sets/results/ncm_sudoku-hard_ours.jsonAdded+64
revision/clue_sets/results/ncm_sudoku-medium_c35.jsonAdded+36
revision/clue_sets/results/ours_rec_full_c30_K1.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c30_K12.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c30_K61.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c35_K1.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c35_K12.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c35_K61.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c40_K1.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c40_K12.jsonAdded+21
revision/clue_sets/results/ours_rec_full_c40_K61.jsonAdded+21
revision/clue_sets/results/ours_rec_full_hard_K1.jsonAdded+49
revision/clue_sets/results/ours_rec_full_hard_K12.jsonAdded+49
revision/clue_sets/results/ours_rec_full_hard_K61.jsonAdded+49
revision/code/count_flops.pyAdded+119
revision/code/eval_same_data.pyAdded+51
revision/code/make_clue_sets.pyAdded+129
revision/code/train_same_data.pyAdded+378
revision/code/train_sudoku.pyAdded+319
revision/compute/compute_flops.jsonAdded+25