"""Sampling + evaluation for the SAT reproduction. Methods (paper Sec 4/6.2, App C.2.2): vanilla : masked-diffusion iterative unmasking, no search. last_step : vanilla trajectory; CSS + local refinement only at the final step. searchdiff : CSS candidates + clause-based local refinement at EVERY step. searchdiff_rand : identical search machinery, candidates from uniform random bits (no learned proposal) - separates learned proposals from search. no_model_search : uniform random 7-bit init + greedy bit-flip hill climbing with a matched evaluator budget (no model at all). Every final assignment is verified by sat_core.check_assignment, which independently re-parses the textual CNF. Wrong-length / missing outputs count as failures. Both denominators (all formulas, satisfiable-only) are reported, using the labels from an exhaustive 128-assignment oracle. """ import argparse import json import math import os import time import numpy as np import torch import torch.nn.functional as F import sat_core as S from train_mdm import MDM EVAL_CALLS = 0 def clause_arrays(text): cls = S.parse_formula_text(text) nv = np.array([[v - 1 for v, _ in cl] for cl in cls], dtype=np.int64) neg = np.array([[int(n) for _, n in cl] for cl in cls], dtype=np.int64) return nv, neg def unsat_counts(nv, neg, assign): """assign: (C,7) array of 0/1. Returns (C,) number of violated clauses.""" global EVAL_CALLS EVAL_CALLS += assign.shape[0] a = np.asarray(assign, dtype=np.int64) vals = np.where(neg[None].astype(bool), 1 - a[:, nv], a[:, nv]) # (C,45,3) sat = vals.any(axis=2) return (~sat).sum(axis=1) def schedule(T, n=7): """cumulative committed count after each step; n_commit[i] = cum[i]-cum[i-1].""" cum = [math.ceil(n * (i + 1) / T) for i in range(T)] return cum @torch.no_grad() def run_batch(model, chunk, method, T, K, max_refine=7, dev="cuda", rand_candidates=False): """One batch through one config. Returns list of (bits_or_None, eval_calls).""" B = len(chunk) ids0 = torch.tensor([S.encode_row(r, None) for r in chunk], device=dev) pad_mask = ids0.ne(S.TOK["PAD"]) committed = torch.full((B, S.N_ASSIGN), -1, dtype=torch.long, device=dev) arrays = [clause_arrays(r["text"]) for r in chunk] cum = schedule(T) prev = 0 for step in range(T): n_commit = cum[step] - prev prev = cum[step] ids = ids0.clone() m = committed >= 0 ids[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] = torch.where( m, committed + S.TOK["0"], torch.full_like(committed, S.TOK["MASK"])) logits = model(ids, pad_mask) probs = F.softmax(logits[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN, :], dim=-1) bp = probs[..., S.TOK["0"]:S.TOK["0"] + 2] # distribution over {bit 0, bit 1} do_search = (method == "searchdiff") or (method == "last_step" and step == T - 1) if not do_search: # vanilla: confidence-ordered commit, sample tokens from the model if n_commit == 0: continue conf = bp.max(-1).values * (committed < 0).float() top = torch.topk(conf, n_commit).indices # (B, n_commit) rowsel = torch.arange(B, device=dev)[:, None].expand(-1, n_commit) sel = bp[rowsel.reshape(-1), top.reshape(-1)].clamp_min(1e-12) # (B*nc, 2) samp = torch.multinomial(sel, 1).reshape(rowsel.shape) # bit values 0/1 committed[rowsel, top] = samp continue # --- CSS: K candidates drawn from the denoiser proposal (single forward) --- maskpos = committed < 0 # (B,7) if rand_candidates: cand = torch.randint(0, 2, (B, K, S.N_ASSIGN), device=dev) cand = torch.where(maskpos[:, None, :], cand, committed.clamp_min(0)[:, None, :]) else: logp = torch.log(bp.clamp_min(1e-12)) noise = -torch.log(-torch.log( torch.rand(B, K, S.N_ASSIGN, 2, device=dev).clamp(1e-20, 1))) cand = (logp[:, None, :, :] + noise).argmax(-1) # (B,K,7) bit values cand = torch.where(maskpos[:, None, :], cand, committed.clamp_min(0)[:, None, :]) cand_np = cand.cpu().numpy() # score all candidates viol = np.empty((B, K), dtype=np.int64) for b in range(B): nv, neg = arrays[b] viol[b] = unsat_counts(nv, neg, cand_np[b]) best = viol.argmin(axis=1) # (B,) cur = cand_np[np.arange(B), best] # (B,7) cur_viol = viol[np.arange(B), best] # --- local refinement: greedy single-bit flips --- for _ in range(max_refine): flips = np.repeat(cur, 7, axis=0) # (B*7,7) idx = np.arange(B * 7) % 7 flips[np.arange(B * 7), idx] = 1 - flips[np.arange(B * 7), idx] fv = np.empty((B, 7), dtype=np.int64) for b in range(B): nv, neg = arrays[b] fv[b] = unsat_counts(nv, neg, flips[b * 7:(b + 1) * 7]) fbest = fv.min(axis=1) imp = fbest < cur_viol if not imp.any(): break pick = fv.argmin(axis=1) # flips[b*7 + j] is candidate b with bit j flipped cur = np.where(imp[:, None], flips[np.arange(B) * 7 + pick], cur) cur_viol = np.where(imp, fbest, cur_viol) # --- commit scheduled positions from the refined candidate --- if n_commit > 0: conf = bp.max(-1).values * maskpos top = torch.topk(conf, n_commit).indices # (B, n_commit) cur_t = torch.from_numpy(cur).to(dev) committed[torch.arange(B, device=dev)[:, None], top] = cur_t[ torch.arange(B, device=dev)[:, None], top] bits = ["".join(str(int(v)) for v in committed[b].tolist()) for b in range(B)] return bits def verify(chunk, bits_list): out = [] for r, bits in zip(chunk, bits_list): if bits is None or len(bits) != 7 or set(bits) - {"0", "1"}: out.append({"id": r["id"], "is_sat": r["is_sat"], "bits": bits, "verified": False, "unsat": None, "failure": "invalid_or_missing"}) continue unsat, total = S.check_assignment(r["text"], bits) out.append({"id": r["id"], "is_sat": r["is_sat"], "bits": bits, "verified": unsat == 0, "unsat": unsat, "failure": None}) return out def summarize(name, per_formula, eval_calls_mean): n_all = len(per_formula) n_sat = sum(1 for f in per_formula if f["is_sat"]) ok_all = sum(1 for f in per_formula if f["verified"]) sat_rows = [f for f in per_formula if f["is_sat"]] ok_sat = sum(1 for f in sat_rows if f["verified"]) return {"config": name, "n_all": n_all, "n_sat_cohort": n_sat, "acc_all_pct": 100.0 * ok_all / n_all, "acc_sat_only_pct": 100.0 * ok_sat / len(sat_rows) if sat_rows else None, "eval_calls_per_formula_mean": eval_calls_mean} def no_model_search(rows, budget, seed): """Control: random init + greedy hill climbing, no model. budget = eval calls.""" rng = np.random.default_rng(seed) per = [] for r in rows: nv, neg = clause_arrays(r["text"]) cur = rng.integers(0, 2, size=7) v0 = unsat_counts(nv, neg, cur[None, :])[0] calls = 1 while calls + 7 <= budget: flips = np.repeat(cur[None, :], 7, axis=0).copy() flips[np.arange(7), np.arange(7)] = 1 - flips[np.arange(7), np.arange(7)] fv = unsat_counts(nv, neg, flips) calls += 7 if fv.min() < v0: cur = flips[fv.argmin()] v0 = fv.min() else: break unsat, _ = S.check_assignment(r["text"], "".join(map(str, cur.tolist()))) per.append({"id": r["id"], "is_sat": r["is_sat"], "bits": "".join(map(str, cur.tolist())), "verified": unsat == 0, "unsat": unsat, "failure": None}) return per def main(): ap = argparse.ArgumentParser() ap.add_argument("--test", default="/work/data/test_all.jsonl") ap.add_argument("--ckpt", default="/work/mdm_sat.pt") ap.add_argument("--out", default="/work/results") ap.add_argument("--batch", type=int, default=64) ap.add_argument("--seeds", type=int, default=3, help="repeats for headline configs") args = ap.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" os.makedirs(args.out, exist_ok=True) rows = [json.loads(l) for l in open(args.test)] n_sat = sum(1 for r in rows if r["is_sat"]) print(f"test set: {len(rows)} formulas, {n_sat} satisfiable " f"({100.0*n_sat/len(rows):.1f}%) [exhaustive oracle]", flush=True) ckpt = torch.load(args.ckpt, map_location=dev, weights_only=False) model = MDM().to(dev) model.load_state_dict(ckpt["state_dict"]) model.eval() summary = [] results_files = {} def run_config(name, method, T, K, seed, rand_candidates=False, subset=None): global EVAL_CALLS EVAL_CALLS = 0 t0 = time.time() rows_use = rows if subset is None else rows[:subset] per = [] for b0 in range(0, len(rows_use), args.batch): chunk = rows_use[b0:b0 + args.batch] bits_list = run_batch(model, chunk, method, T, K, dev=dev, rand_candidates=rand_candidates) per.extend(verify(chunk, bits_list)) ec = EVAL_CALLS / len(rows_use) s = summarize(f"{name}_seed{seed}", per, ec) s["seconds"] = round(time.time() - t0, 1) summary.append(s) results_files[s["config"]] = per print(json.dumps(s), flush=True) # headline configs, 3 seeds for seed in range(args.seeds): run_config("vanilla_T20", "vanilla", 20, 0, seed) run_config("searchdiff_T20_K32", "searchdiff", 20, 32, seed) run_config("last_step_T20", "last_step", 20, 32, seed) sd_budget = summary[1]["eval_calls_per_formula_mean"] for seed in range(args.seeds): per = no_model_search(rows, int(round(sd_budget)), 100 + seed) s = summarize(f"no_model_search_seed{seed}", per, sd_budget) summary.append(s) results_files[s["config"]] = per print(json.dumps(s), flush=True) # T sweep, seed 0 for T in (1, 5, 10, 15): run_config(f"vanilla_T{T}", "vanilla", T, 0, 0) run_config(f"searchdiff_T{T}_K32", "searchdiff", T, 32, 0) for T in (5, 10, 15): run_config(f"last_step_T{T}", "last_step", T, 32, 0) # candidate-count sweep at T=20 (search budget sensitivity), seed 0 for K in (1, 8, 128): run_config(f"searchdiff_T20_K{K}", "searchdiff", 20, K, 0) run_config("searchdiff_rand_T20_K32", "searchdiff", 20, 32, 0, rand_candidates=True) with open(os.path.join(args.out, "summary.json"), "w") as f: json.dump(summary, f, indent=1) with open(os.path.join(args.out, "per_formula.json"), "w") as f: json.dump(results_files, f) print("WROTE", args.out, flush=True) if __name__ == "__main__": main()