"""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 is not a reproduction of the authors' original training implementation or budget. """ import argparse import shutil import csv import hashlib import json import math from pathlib import Path import random import subprocess import sys import time import numpy as np import torch import torch.nn.functional as F from 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