Download train_mdm.py from Rami/searchdiff-sat-repro: direct link, hf CLI and curl.
- Browser
- Download file 8.59 kB
-
https://huggingface.co/Rami/searchdiff-sat-repro/resolve/main/train_mdm.py
- Command line
-
hf download hf://Rami/searchdiff-sat-repro/train_mdm.py
-
curl -L -o train_mdm.py https://huggingface.co/Rami/searchdiff-sat-repro/resolve/main/train_mdm.py
8.59 kB
| """Train a ~6M-parameter bidirectional masked-diffusion model (GPT-2 style, no causal | |
| mask) on FORMULA[SEP]ASSIGNMENT for random 3-SAT, per paper Sec 6.2. | |
| Deviation note: minimal MDLM-style absorbing diffusion (linear schedule), since the | |
| author repo ships no symbolic code; the paper gives only "standard masked diffusion | |
| objective" for a GPT-2-style bidirectional denoiser. | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import random | |
| import time | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import sat_core as S | |
| D, LAYERS, HEADS, FF, SEQ = 224, 6, 8, 1792, S.SEQ_LEN | |
| class Block(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.ln1 = nn.LayerNorm(D) | |
| self.qkv = nn.Linear(D, 3 * D) | |
| self.proj = nn.Linear(D, D) | |
| self.ln2 = nn.LayerNorm(D) | |
| self.fc1 = nn.Linear(D, FF) | |
| self.fc2 = nn.Linear(FF, D) | |
| def forward(self, x, pad_mask): | |
| B, T, _ = x.shape | |
| h = self.ln1(x) | |
| q, k, v = self.qkv(h).chunk(3, dim=-1) | |
| q = q.view(B, T, HEADS, -1).transpose(1, 2) | |
| k = k.view(B, T, HEADS, -1).transpose(1, 2) | |
| v = v.view(B, T, HEADS, -1).transpose(1, 2) | |
| att = (q @ k.transpose(-2, -1)) / math.sqrt(q.size(-1)) | |
| att = att.masked_fill(~pad_mask[:, None, None, :], float("-inf")) | |
| att = att.softmax(dim=-1) | |
| o = (att @ v).transpose(1, 2).reshape(B, T, D) | |
| x = x + self.proj(o) | |
| x = x + self.fc2(F.gelu(self.fc1(self.ln2(x)))) | |
| return x | |
| class MDM(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.emb = nn.Embedding(len(S.VOCAB), D) | |
| self.pos = nn.Embedding(SEQ, D) | |
| self.blocks = nn.ModuleList(Block() for _ in range(LAYERS)) | |
| self.ln_f = nn.LayerNorm(D) | |
| self.head = nn.Linear(D, len(S.VOCAB), bias=False) | |
| self.head.weight = self.emb.weight # tied | |
| def forward(self, ids, pad_mask): | |
| x = self.emb(ids) + self.pos(torch.arange(SEQ, device=ids.device))[None] | |
| for b in self.blocks: | |
| x = b(x, pad_mask) | |
| return self.head(self.ln_f(x)) | |
| def encode_batch(rows, targets, device): | |
| ids = torch.tensor([S.encode_row(r, t) for r, t in zip(rows, targets)], device=device) | |
| pad_mask = ids.ne(S.TOK["PAD"]) | |
| return ids, pad_mask | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--train", default="/work/data/train_sat.jsonl") | |
| ap.add_argument("--val", default="/work/data/val_sat.jsonl") | |
| ap.add_argument("--out", default="/work/mdm_sat.pt") | |
| ap.add_argument("--steps", type=int, default=25000) | |
| ap.add_argument("--batch", type=int, default=512) | |
| ap.add_argument("--lr", type=float, default=3e-4) | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| torch.manual_seed(args.seed) | |
| random.seed(args.seed) | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| print("device:", dev, flush=True) | |
| train = [json.loads(l) for l in open(args.train)] | |
| val = [json.loads(l) for l in open(args.val)] | |
| assert len(train) > 0 and all(r["is_sat"] and r["train_target"] for r in train) | |
| print(f"train {len(train)} sat formulas, val {len(val)}", flush=True) | |
| model = MDM().to(dev) | |
| n_params = sum(p.numel() for p in model.parameters()) | |
| print(f"params: {n_params/1e6:.2f}M", flush=True) | |
| opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) | |
| sched = torch.optim.lr_scheduler.LambdaLR( | |
| opt, lambda s: min(1.0, s / 500) * (1 if s < args.steps * 0.9 else max(0.05, (args.steps - s) / (args.steps * 0.1)))) | |
| import trackio | |
| trackio.init(project="searchdiff-sat-repro", space_id="Rami/searchdiff-sat-repro-trackio", | |
| config={"steps": args.steps, "batch": args.batch, "params_M": round(n_params / 1e6, 2)}) | |
| n = len(train) | |
| t0 = time.time() | |
| def build(rows): | |
| ids_list, lab_list = [], [] | |
| for r in rows: | |
| tgt = r["train_target"] | |
| toks = S.encode_formula(r["text"]) + [S.TOK[b] for b in tgt] | |
| toks += [S.TOK["PAD"]] * (SEQ - len(toks)) | |
| labs = ([-100] * S.ASSIGN_START + [S.TOK[b] for b in tgt] | |
| + [-100] * (SEQ - S.ASSIGN_START - S.N_ASSIGN)) | |
| ids_list.append(toks) | |
| lab_list.append(labs) | |
| return torch.tensor(ids_list, device=dev), torch.tensor(lab_list, device=dev) | |
| train_ids, train_labs = build(train) # clean ids; masked on-GPU per step | |
| val_ids, val_labs = build(val) | |
| for step in range(1, args.steps + 1): | |
| idx = torch.randint(0, n, (args.batch,), device=dev) | |
| ids = train_ids[idx].clone() | |
| labs = train_labs[idx] | |
| t = torch.rand(args.batch, device=dev).clamp_min(0.02) # mask prob per sample | |
| drop = torch.rand(args.batch, S.N_ASSIGN, device=dev) < t[:, None] | |
| assign = ids[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] | |
| assign = torch.where(drop, torch.full_like(assign, S.TOK["MASK"]), assign) | |
| ids[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] = assign | |
| labels = torch.where(drop, labs[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN], | |
| torch.full_like(labs[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN], -100)) | |
| pad_mask = ids.ne(S.TOK["PAD"]) | |
| logits = model(ids, pad_mask) | |
| assign_logits = logits[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN, :] | |
| ce = F.cross_entropy(assign_logits.reshape(-1, len(S.VOCAB)), labels.reshape(-1), | |
| reduction="none", ignore_index=-100).view(args.batch, S.N_ASSIGN) | |
| denom = ce.ne(0).sum() | |
| if denom.item() == 0: | |
| continue | |
| # MDLM-style 1/t weighting on masked positions (per-sample NELBO estimate) | |
| w = 1.0 / t | |
| loss = (ce.sum(dim=1) * w).mean() / S.N_ASSIGN | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| sched.step() | |
| if step % 200 == 0: | |
| print(f"step {step} loss {loss.item():.4f} lr {sched.get_last_lr()[0]:.2e} " | |
| f"({(time.time()-t0)/step:.3f}s/step)", flush=True) | |
| trackio.log({"train/loss": loss.item(), "train/lr": sched.get_last_lr()[0]}, step=step) | |
| if step % 2000 == 0: | |
| torch.save({"state_dict": model.state_dict(), "config": {"D": D, "LAYERS": LAYERS, | |
| "HEADS": HEADS, "FF": FF, "SEQ": SEQ, "vocab": S.VOCAB}}, args.out) | |
| print(f"checkpoint saved at step {step}", flush=True) | |
| if step % 1000 == 0: | |
| model.eval() | |
| with torch.no_grad(): | |
| # val CE under the SAME masking process (t=0.5), unweighted, | |
| # over held-out formulas never trained on | |
| vg = torch.Generator(device=dev).manual_seed(123) | |
| vloss, vtot = 0.0, 0 | |
| for i in range(0, len(val_ids), 256): | |
| vid = val_ids[i:i + 256].clone() | |
| vlab = val_labs[i:i + 256, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] | |
| Bv = vid.shape[0] | |
| dropv = torch.rand(Bv, S.N_ASSIGN, device=dev, generator=vg) < 0.5 | |
| assign_v = vid[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] | |
| vid[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] = torch.where( | |
| dropv, torch.full_like(assign_v, S.TOK["MASK"]), assign_v) | |
| lg = model(vid, vid.ne(S.TOK["PAD"])) | |
| al = lg[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN, :] | |
| ce_v = F.cross_entropy(al.reshape(-1, len(S.VOCAB)), vlab.reshape(-1), | |
| reduction="none", ignore_index=-100).view(Bv, S.N_ASSIGN) | |
| vloss += ce_v.sum().item() | |
| vtot += dropv.float().sum().item() | |
| vloss /= max(vtot, 1) | |
| print(f"step {step} val_ce {vloss:.4f}", flush=True) | |
| trackio.log({"val/ce": vloss}, step=step) | |
| model.train() | |
| os.makedirs(os.path.dirname(args.out), exist_ok=True) | |
| torch.save({"state_dict": model.state_dict(), "config": {"D": D, "LAYERS": LAYERS, | |
| "HEADS": HEADS, "FF": FF, "SEQ": SEQ, "vocab": S.VOCAB}}, args.out) | |
| print("saved", args.out, flush=True) | |
| if "vloss" in locals(): | |
| trackio.log({"final/val_ce": vloss}) | |
| trackio.finish() | |
| if __name__ == "__main__": | |
| main() | |