Fixes: NCM same-data training artifacts and curves
Browse filesFiles changed (7)
- Fixes/ncm-same-data-s0/README.mdAdded+59
- Fixes/ncm-same-data-s0/config.yamlAdded+115
- Fixes/ncm-same-data-s0/manifest.jsonAdded+40
- Fixes/ncm-same-data-s0/ncm_encoding.pyAdded+91
- Fixes/ncm-same-data-s0/smoke_checks.jsonAdded+72
- Fixes/ncm-same-data-s0/tokenizer_training.csvAdded+6
- Fixes/ncm-same-data-s0/train_same_data.pyAdded+339
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# NCM on the project's training split
`train_same_data.py` trains the official NCM modules in two stages: a randomlyinitialized multiscale VQ-VAE on training solutions, followed by a randomlyinitialized conditional generator with the codec frozen. No published weightsare loaded. Both stages use paired digit relabeling; only the generator consumespuzzle prefixes. All 100,000 training puzzles are eligible for sampling.
The upstream inference release has no training entry point. This is our trainingloop around those modules, **not a reproduction of the authors' trainer**.The architecture configuration and upstream commit are archived with each run.
## Budget and interpretation
This single-seed experiment is limited to a $10 Lambda rental. The nominaltargets are 10,000 tokenizer updates and 50,000 generator updates, batch 256rather than the paper's 1,024. The tokenizer is limited to 30 minutes so thatthe generator also receives training time. A fixed absolute training deadlinereserves time for evaluation, graphs, and artifact collection before termination.The manifest records actual updates, examples seen, parameter counts, timing,training-array SHA-256 hashes, and whether a stage stopped early.
A budget-limited or poorly reconstructed tokenizer can constrain generatoraccuracy. Low accuracy must not be presented as a failure of the published NCMmethod. Training compute is not matched to the recurrent baseline. This runremoves the different-training-split confound, not every experimental difference.
The official dropout and quantization modules are used. Gradient accumulationsplits a batch into microbatches; codebook EMA decay is adjusted so the effectiveper-optimizer-update decay remains 0.99. Nested dropout is sampled per microbatch.Learning-rate schedules retain the nominal update counts if time expires early.
## Checks and outputs
`--smoke` runs two updates per stage using training arrays only. It checks finitelosses, gradient flow to the learned first-level query, independence of thefirst-level logits from future solution codes, and end-to-end generation shapes.
Normal training opens test arrays only after the final generator checkpoint.It reports exact board accuracy, legal-board rate, clue preservation, malformedseparator rate, and per-puzzle predictions. There is no test-based checkpointselection. Training reconstruction diagnostics are labeled as training data.
Artifacts include final weights, optimizer/RNG checkpoints, CSV training curves,`training_curves.png`, configuration, source, manifest, predictions, and results.The requested public destination is`GOVINDFROM/parallel-consistent-masked-diffusion/Fixes/ncm-same-data-s0/`.Account credentials remain on the local machine; local synchronization uploadsonly the artifact directory. The instance is protected by a local terminationwatchdog with sleep prevention; a remote shutdown timer provides a secondaryworkload stop. Instance termination, not OS shutdown, ends cloud billing.
Example (set the absolute epoch deadline for the rental before executing):
```bashpython ncm/train_same_data.py --upstream /path/to/HazyResearch-ncm \ --data data/sudoku_hard --out runs/ncm-same-data-s0 \ --batch 256 --micro-batch 64 --train-until "$TRAIN_UNTIL"```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115task: sudoku-hardcheckpoints: generator: generator.pt tokenizer: tokenizer.ptdata: test: puzzles.pickle test_refs: solutions.picklemodel: n_layer: 8 n_head: 8 bias: true dropout: 0.1 n_embd: 512 context_length: 180 vocab_size: - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 attn_pattern: block_diagonal use_positional_encoding: true use_level_encoding: true prefix_len: 91 use_rope: true rope_base: 10000 use_qk_norm: true raw_token_prefix: true query_level0: true tie_heads_to_codebook: falsetokenizer: pre_tokenizer: name: sudoku tokenizer: sudoku vqvae: n_layers: 4 context_length: 89 embed_dim: 256 in_vocab_size: 12 vqvae_vocab_size: - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 - 16 compression_factor: 1 dropout: 0.3 dec_layers: 1 pre_quant_dropout: 0.0 pre_quant_groupnorm: 8 pre_quant_norm_type: group use_qk_norm: true vector_quantizer_config: clss: multiscale_residual_vector_quantizer decay: 0.99 epsilon: 1.0e-05 commitment_cost: 0.25 learned_l1_sampling: true learned_all_sampling: false quant_resi: enabled: true ratio: 0.5 share_mode: 0 learnable_ratio: false levels: use_manual_levels: true manual_levels: - 1 - 2 - 4 - 6 - 9 - 13 - 18 - 26 - 37 - 50 - 67 - 89 learned_l1_cascade: true learned_l1_cascade_base: 4 learned_l1_cascade_norm: false learned_l1_cascade_norm_final: false aux: fine_drop: prob: 0.5 min_keep: 1 checkpoint_path: tokenizer.ptgeneration: soft_decisions: true soft_temperature: 3.75 temperature: 0.0 top_k: 0 top_p: 1.0 cfg_scale: 0.0eval: split: test n_docs: 2000 batch_size: 128 n_shards: 2 metric: exact12345678910111213141516171819202122232425262728293031323334353637383940{ "experiment": "NCM trained from scratch on our exact training split", "initialization": "random for both codec and generator; no pretrained weights", "upstream_commit": "af2cf6f63d4b4a1f8b0906a16388d6753f240992", "train_examples": 100000, "train_sha256": { "train_puz.npy": "a3a25e429e7f846838249e00def6e94280f06748b9d9a305ad0fd281ba0fb139", "train_sol.npy": "28e94251ef9fd901ca6ebe78415dbb290fc9ec42114f283dd3c07b6eec7b5b96" }, "seed": 0, "args": { "upstream": "/home/ubuntu/ncm-work/upstream", "data": "/home/ubuntu/ncm-work/data/sudoku_hard", "out": "/home/ubuntu/ncm-work/artifacts", "seed": 0, "tokenizer_steps": 10000, "generator_steps": 50000, "batch": 256, "micro_batch": 64, "tokenizer_max_seconds": 1800, "train_until": 1796446199.0, "hf_repo": "", "hf_prefix": "Fixes/ncm-same-data-s0", "device": "cuda", "smoke": false }, "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": 1796431327.6697106}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Board encoding for the public NCM Sudoku exports, plus scoring.
The exported graphs take a single `prefix` of 91 int64 tokens and return thecodes and tokens of all 12 levels. The encoding is not documented anywhereexcept in the demo code that ships with the exports, so it is reproduced hereand checked against the shipped fixtures by `verify_export.py` before anynumber from these models is trusted.
Layout: EDGE, then nine rows of nine cells separated by SEP, then EDGE.A blank cell is 0 and a clue is its digit 1-9, which is exactly how our own`test_puz.npy` stores a puzzle, so no conversion is needed on our side."""import numpy as np
SEP, EDGE = 10, 11GRID, CELLS = 9, 81PREFIX_LEN = 1 + CELLS + (GRID - 1) + 1 # 91LEVEL_LEN = CELLS + (GRID - 1) # 89, one decoded level
def encode_board(cells): """81 cells (0 for blank) -> the 91-token prefix the export expects.""" if len(cells) != CELLS: raise ValueError(f"expected {CELLS} cells, got {len(cells)}") out = [EDGE] for r in range(GRID): if r: out.append(SEP) out.extend(int(v) for v in cells[r * GRID:(r + 1) * GRID]) out.append(EDGE) if len(out) != PREFIX_LEN: raise AssertionError(f"prefix is {len(out)} tokens, expected {PREFIX_LEN}") return out
def decode_cells(tokens): """Strip the separators from one level and return its 81 cells.""" cells = [int(t) for t in tokens if t not in (SEP, EDGE)] if len(cells) != CELLS: raise ValueError(f"decoded {len(cells)} cells, expected {CELLS}") return cells
def levels_from_output(tokens): """Split a flat `tokens` output into one row per level.""" flat = np.asarray(tokens).reshape(-1) if flat.size % LEVEL_LEN: raise ValueError(f"output of {flat.size} tokens is not a multiple of {LEVEL_LEN}") return flat.reshape(-1, LEVEL_LEN)
def is_legal(cells): """Every row, column and box holds each digit 1-9 exactly once.
This is the validity-only metric the NCM paper reports as Valid Puzzle Rate. It is weaker than board accuracy: a legal board that ignores the clues still counts as valid under it. """ g = np.asarray(cells, dtype=int).reshape(GRID, GRID) if g.min() < 1 or g.max() > 9: return False want = set(range(1, 10)) if any(set(row) != want for row in g): return False if any(set(col) != want for col in g.T): return False for r in (0, 3, 6): for c in (0, 3, 6): if set(g[r:r + 3, c:c + 3].reshape(-1)) != want: return False return True
def keeps_clues(cells, puzzle): """The output agrees with every given clue.""" return all(p == 0 or int(p) == int(c) for p, c in zip(puzzle, cells))
def score(cells, puzzle, solution): """The three numbers we report per puzzle.
`board` is our metric: all 81 cells match the unique solution. `legal` and `clues` are reported beside it so the comparison with the NCM paper's validity-only metric is explicit rather than implied. """ cells = [int(v) for v in cells] return { "board": all(int(s) == c for s, c in zip(solution, cells)), "legal": is_legal(cells), "clues": keeps_clues(cells, puzzle), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "experiment": "NCM trained from scratch on our exact training split", "initialization": "random for both codec and generator; no pretrained weights", "upstream_commit": "af2cf6f63d4b4a1f8b0906a16388d6753f240992", "train_examples": 100000, "train_sha256": { "train_puz.npy": "a3a25e429e7f846838249e00def6e94280f06748b9d9a305ad0fd281ba0fb139", "train_sol.npy": "28e94251ef9fd901ca6ebe78415dbb290fc9ec42114f283dd3c07b6eec7b5b96" }, "seed": 0, "args": { "upstream": "upstream", "data": "data/sudoku_hard", "out": "smoke", "seed": 0, "tokenizer_steps": 10000, "generator_steps": 50000, "batch": 8, "micro_batch": 4, "tokenizer_max_seconds": 1800, "train_until": 1796431833.8216882, "hf_repo": "", "hf_prefix": "Fixes/ncm-same-data-s0", "device": "cuda", "smoke": true }, "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": "smoke_passed", "started_at_epoch": 1796431238.102769, "tokenizer": { "steps_completed": 2, "steps_planned": 2, "global_batch": 8, "examples_seen": 16, "seconds": 1.4907841682434082, "parameters": 14896512, "budget_limited": false }, "tokenizer_train_reconstruction": { "n": 128, "token_accuracy": 0.10112359374761581, "exact_sequence_accuracy": 0.0 }, "generator": { "steps_completed": 2, "steps_planned": 2, "global_batch": 8, "examples_seen": 16, "seconds": 0.7359130382537842, "parameters": 25457600, "budget_limited": false }, "training_seconds": 2.683544874191284, "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" ], "finished_at_epoch": 1796431241.3363314}123456step,loss,lr,elapsed_seconds,examples_seen
1,4.0275309681892395,1e-06,1.03251051902771,256
10,3.8055996894836426,1e-05,2.2465004920959473,2560
20,3.6504504084587097,2e-05,3.5600674152374268,5120
30,3.262933373451233,2.9999999999999997e-05,4.873562812805176,7680
40,3.3025457859039307,4e-05,6.1850266456604,10240123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""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 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') 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 = {} last_sync = time.time() start = time.time() for stage in ['tokenizer', 'generator']: 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) completed = 0 stage_start = time.time() logpath = a.out / (stage + '_training.csv') with logpath.open('w', buffering=1) as logfile: writer = csv.DictWriter(logfile, fieldnames=['step','loss','lr','elapsed_seconds','examples_seen']) writer.writeheader() for step in range(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()Fixes/ncm-same-data-s0/README.mdAdded+59
Fixes/ncm-same-data-s0/config.yamlAdded+115
Fixes/ncm-same-data-s0/manifest.jsonAdded+40
Fixes/ncm-same-data-s0/ncm_encoding.pyAdded+91
Fixes/ncm-same-data-s0/smoke_checks.jsonAdded+72
Fixes/ncm-same-data-s0/tokenizer_training.csvAdded+6
Fixes/ncm-same-data-s0/train_same_data.pyAdded+339