Download Fixes/ncm-same-data-s0/train_same_data.py from GOVINDFROM/parallel-consistent-masked-diffusion: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/GOVINDFROM/parallel-consistent-masked-diffusion/resolve/main/Fixes/ncm-same-data-s0/train_same_data.py
- Command line
-
hf download hf://GOVINDFROM/parallel-consistent-masked-diffusion/Fixes/ncm-same-data-s0/train_same_data.py
-
curl -L -o train_same_data.py https://huggingface.co/GOVINDFROM/parallel-consistent-masked-diffusion/resolve/main/Fixes/ncm-same-data-s0/train_same_data.py
17.7 kB
| """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 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') | |
| 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() | |