File size: 4,896 Bytes
50b6741 | 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 | """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)
|