fibs-v1 / provenance /build_longcontext_single_turn_split.py
chrisjcundy's picture
Re-render the 1,085 single-turn longcontext rows as four messages (passage + ack, filler, preamble + question, completion)
65dccf1 verified
Raw History Blame Contribute Delete
5.86 kB
"""Build the FIBS-v1 revision that re-renders the 1,085 single-turn longcontext rows as four messages.
Parent: AlignmentResearch/fibs-v1 @ 1596f18267bc45e14f9a08d0f9949015ce0b1d2b (local byte-identical copy under SRC).
Only `messages_json` changes, only on rows of family longcontext whose message list has exactly one user turn and whose
user turn ends in a horizontal-rule separator followed by the question. Every other row and column is copied unchanged.
Variant choice is keyed on sha256(original messages_json), so the build is reproducible from the parent alone.
"""
import hashlib, json, re, sys, os, datetime
import pyarrow as pa, pyarrow.parquet as pq, pyarrow.compute as pc
pa.set_cpu_count(1); pa.set_io_thread_count(1)
SRC = "/home/dev/persistent/SCRATCH/rm_scaling_whitebox/q39_fibs_v1/source"
OUT = sys.argv[1]
SEP = re.compile(r"\n[ \t]*(?:-{3,}|\*{3,})[ \t]*\n?")
FILLERS = ["Acknowledged.", "Understood.", "Got it.", "Noted.", "Okay, I've read it.", "I've read the passage.",
"Read and noted.", "Understood, I have the text.", "Okay.", "Got it, go ahead.", "Noted. Ready for your question.",
"I have it.", "Acknowledged, ready when you are.", "Understood. What would you like to know?", "Read it.",
"Okay, I've gone through it.", "Noted, thanks.", "All read.", "Received and read.", "Understood, ask away."]
REQUESTS = ["Reply with a brief acknowledgement only; I'll ask my question next.",
"Just confirm you've read this, nothing else. My question follows.",
"Please acknowledge in one short line and wait for my question.",
"No response needed beyond a short acknowledgement. Question coming next.",
"Acknowledge briefly that you have read the above; I will ask about it in a moment."]
PREAMBLES = ["Now, about what you just read:", "Here is my question about the passage:", "Based on the text above,",
"Referring to what I showed you:", "My question:", "About the passage you just read:",
"Okay. From the text above,", "Thanks. Now,", "Right, here's the question:", ""]
SINGLE_TURN_SOURCES = {"longcontext_v3_bookqa", "longcontext_lc3flip", "longcontext_lc5flip", "longcontext_v5a_onpolicy",
"longcontext_v5c3_intrace", "longcontext_v5c5_novels"}
def pick(seq, key, salt): return seq[int(hashlib.sha256(f"{salt}:{key}".encode()).hexdigest(), 16) % len(seq)]
def rewrite(mj, source):
msgs = json.loads(mj)
users = [m for m in msgs if m["role"] == "user"]
if source not in SINGLE_TURN_SOURCES or len(users) != 1: return None, "not single-turn"
u = users[0]["content"]; hits = list(SEP.finditer(u))
if not hits: return None, "no separator"
m = hits[-1]; passage, question = u[:m.start()].rstrip(), u[m.end():].strip()
if not question or len(question) > 800: return None, "question length"
key = hashlib.sha256(mj.encode()).hexdigest()
final_user = question if "\n" in question else (pick(PREAMBLES, key, "pre") + " " + question).strip()
new = [m for m in msgs if m["role"] == "system"] + [
{"role": "user", "content": passage + "\n\n" + pick(REQUESTS, key, "req")},
{"role": "assistant", "content": pick(FILLERS, key, "fill")},
{"role": "user", "content": final_user}]
assert [m["role"] for m in msgs if m["role"] not in ("system", "user")] == [], "unexpected roles in single-turn row"
return json.dumps(new, ensure_ascii=False), key
os.makedirs(f"{OUT}/data", exist_ok=True); os.makedirs(f"{OUT}/provenance", exist_ok=True)
record = {"parent_repo": "AlignmentResearch/fibs-v1", "parent_revision": "1596f18267bc45e14f9a08d0f9949015ce0b1d2b", "parent_parquet_sha256": {},
"rule": "family longcontext, one user turn, split at the last horizontal-rule line; messages_json only", "sources": sorted(SINGLE_TURN_SOURCES),
"fillers": FILLERS, "requests": REQUESTS, "preambles": PREAMBLES, "variant_key": "sha256(original messages_json), salted 'req'/'fill'/'pre'",
"rows": [], "skipped": [], "builder_sha256": hashlib.sha256(open(__file__, "rb").read()).hexdigest(), "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat()}
for quad in ("deceptive_deceptive", "deceptive_honest", "honest_deceptive", "honest_honest"):
fn = f"data/{quad}-00000-of-00001.parquet"; record["parent_parquet_sha256"][quad] = hashlib.sha256(open(f"{SRC}/{fn}", "rb").read()).hexdigest()
t = pq.read_table(f"{SRC}/{fn}")
mj_col = t.column("messages_json").to_pylist(); fam = pc.equal(t.column("deception_type"), "longcontext")
src_col = t.column("source").to_pylist(); n_changed = 0; new_col = list(mj_col)
# family lives in `deception_type`? check quickly against source prefix; the census used `family` from source
for i, (mj, src) in enumerate(zip(mj_col, src_col)):
if not str(src).startswith("longcontext"): continue
new, info = rewrite(mj, src)
if new is None: record["skipped"].append({"quadrant": quad, "row": i, "source": src, "why": info}); continue
new_col[i] = new; n_changed += 1; record["rows"].append({"quadrant": quad, "row": i, "source": src, "orig_messages_sha256": info})
idx = t.schema.get_field_index("messages_json")
t2 = t.set_column(idx, pa.field("messages_json", pa.string()), pa.array(new_col, type=pa.string()))
t2 = t2.replace_schema_metadata(t.schema.metadata)
pq.write_table(t2, f"{OUT}/{fn}", compression="snappy", row_group_size=1000)
print(f"{quad}: rows {t.num_rows}, rewritten {n_changed}")
record["n_rewritten"] = len(record["rows"]); record["n_skipped"] = len(record["skipped"])
json.dump(record, open(f"{OUT}/provenance/longcontext_single_turn_split.json", "w"), indent=1, ensure_ascii=False)
print("total rewritten", record["n_rewritten"], "skipped", record["n_skipped"], {s["why"] for s in record["skipped"]})