Download sat_core.py from Rami/searchdiff-sat-repro: direct link, hf CLI and curl.
- Browser
- Download file 4.9 kB
-
https://huggingface.co/Rami/searchdiff-sat-repro/resolve/main/sat_core.py
- Command line
-
hf download hf://Rami/searchdiff-sat-repro/sat_core.py
-
curl -L -o sat_core.py https://huggingface.co/Rami/searchdiff-sat-repro/resolve/main/sat_core.py
4.9 kB
| """Random 3-SAT data generation, exhaustive oracle, tokenizer, and an INDEPENDENT checker. | |
| Task spec (paper Sec 6.2 / App C.2.2): random 3-SAT, n=7 variables, 45 clauses, | |
| instance = FORMULA[SEP]ASSIGNMENT (7 bits). Metric: fraction of test formulas whose | |
| submitted 7-bit assignment satisfies every clause, verified by independent parse. | |
| """ | |
| import json | |
| import random | |
| NVARS = 7 | |
| NCLAUSES = 45 | |
| K = 3 | |
| # ---------------- generation ---------------- | |
| def gen_formula(rng): | |
| """One random 3-CNF formula: 45 clauses, 3 distinct vars each, negation p=0.5.""" | |
| clauses = [] | |
| for _ in range(NCLAUSES): | |
| vs = rng.sample(range(1, NVARS + 1), K) | |
| clauses.append([(v, rng.random() < 0.5) for v in vs]) | |
| return clauses | |
| def clause_to_text(clause): | |
| return "(" + "|".join(("~" if neg else "") + "x%d" % v for v, neg in clause) + ")" | |
| def formula_to_text(clauses): | |
| return " & ".join(clause_to_text(c) for c in clauses) | |
| # ---------------- INDEPENDENT checker (parses the text, never the generator object) ---------------- | |
| def parse_formula_text(text): | |
| clauses = [] | |
| for cl in text.split(" & "): | |
| assert cl.startswith("(") and cl.endswith(")"), cl | |
| lits = [] | |
| for tok in cl[1:-1].split("|"): | |
| neg = tok.startswith("~") | |
| lits.append((int(tok.lstrip("~")[1:]), neg)) | |
| clauses.append(lits) | |
| return clauses | |
| def check_assignment(text, bits): | |
| """bits: 7-char string 'b1..b7', b_i is the value of x_i. Returns (#unsat, total).""" | |
| assert len(bits) == 7 and set(bits) <= {"0", "1"}, bits | |
| a = tuple(int(b) for b in bits) # a[i] = value of x_{i+1} | |
| unsat = 0 | |
| for cl in parse_formula_text(text): | |
| if not any((a[v - 1] == (0 if neg else 1)) for v, neg in cl): | |
| unsat += 1 | |
| return unsat, len(parse_formula_text(text)) | |
| # ---------------- exhaustive oracle ---------------- | |
| def oracle(text): | |
| """Exhaustively test all 128 assignments (vectorized). Returns (is_sat, [solutions]).""" | |
| import numpy as np | |
| cls = parse_formula_text(text) | |
| nv = np.array([[v - 1 for v, _ in cl] for cl in cls], dtype=np.int64) # (45,3) | |
| neg = np.array([[int(n) for _, n in cl] for cl in cls], dtype=bool) # (45,3) | |
| # (128,7): column i is x_{i+1}, matching format(n,'07b') = 'b1..b7' | |
| bits = ((np.arange(128)[:, None] >> np.arange(6, -1, -1)[None, :]) & 1).astype(np.int64) | |
| vals = np.where(neg[None], 1 - bits[:, nv], bits[:, nv]) # (128,45,3) | |
| unsat = (~vals.any(axis=2)).sum(axis=1) # (128,) | |
| idx = np.where(unsat == 0)[0] | |
| sols = ["".join(map(str, bits[i].tolist())) for i in idx] | |
| return len(sols) > 0, sols | |
| # ---------------- datasets ---------------- | |
| def make_inventory(n_formulas, seed, keep="all"): | |
| """keep: 'all' | 'sat'""" | |
| rng = random.Random(seed) | |
| out = [] | |
| i = 0 | |
| while len(out) < n_formulas: | |
| f = gen_formula(rng) | |
| text = formula_to_text(f) | |
| is_sat, sols = oracle(text) | |
| if keep == "sat" and not is_sat: | |
| continue | |
| sol = sols[0] if sols else None # lexicographically-smallest satisfying assignment | |
| out.append({"id": i, "text": text, "is_sat": is_sat, | |
| "n_solutions": len(sols), "train_target": sol}) | |
| i += 1 | |
| return out | |
| def write_jsonl(path, rows): | |
| with open(path, "w") as f: | |
| for r in rows: | |
| f.write(json.dumps(r) + "\n") | |
| # ---------------- tokenizer ---------------- | |
| # Layout: per clause [lit, lit, lit, ";"] (45x4=180), "SEP", 7 assignment tokens = 188. Pad to 192. | |
| LITS = ["x%d" % i for i in range(1, 8)] + ["~x%d" % i for i in range(1, 8)] | |
| VOCAB = LITS + [";", "SEP", "0", "1", "MASK", "PAD"] | |
| TOK = {t: i for i, t in enumerate(VOCAB)} | |
| SEQ_LEN = 192 | |
| ASSIGN_START = 181 # 0-based index of first assignment token (SEP sits at 180) | |
| N_ASSIGN = 7 | |
| def lit_token(v, neg): | |
| return ("~x%d" if neg else "x%d") % v | |
| def encode_formula(text): | |
| toks = [] | |
| for cl in parse_formula_text(text): | |
| for v, neg in cl: | |
| toks.append(TOK[lit_token(v, neg)]) | |
| toks.append(TOK[";"]) | |
| toks.append(TOK["SEP"]) | |
| assert len(toks) == ASSIGN_START, len(toks) | |
| return toks | |
| def encode_row(row, target=None): | |
| """Returns full token ids. target: 7-char bitstring, else MASK everywhere.""" | |
| toks = encode_formula(row["text"]) | |
| if target is None: | |
| toks += [TOK["MASK"]] * N_ASSIGN | |
| else: | |
| assert len(target) == N_ASSIGN | |
| toks += [TOK[b] for b in target] | |
| toks += [TOK["PAD"]] * (SEQ_LEN - len(toks)) | |
| return toks | |
| def decode_bits(ids): | |
| """Extract the 7-char bitstring after SEP; None if any slot is not 0/1.""" | |
| bits = [] | |
| for j in range(ASSIGN_START, ASSIGN_START + N_ASSIGN): | |
| t = VOCAB[ids[j]] | |
| if t in ("0", "1"): | |
| bits.append(t) | |
| else: | |
| return None | |
| return "".join(bits) | |