File size: 11,235 Bytes
eac1a6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | """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()
|