Files
leleka/scripts/quality/q_prep.py
T

87 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""Offline data preparation for the quality gate. Runs on the GPU server, writes only under OUT.
usage: q_prep.py OUT [--orig-out FILE] [--requests FILE] [--port-log TAG=FILE[@ARM] ...] [--free-run TAG=RUNDIR ...]
Writes, for the six-prompt corpus of ~/work/gpu-runs/prompts.txt:
OUT/cases/<name>.ids comma-separated token ids: the prompt followed by one engine's greedy tokens
OUT/cases/meta.json {name: {"n_prompt": N, "prompt": i, "source": ...}}
OUT/force/c<i>.truth the Original's pass-0 sequence per prompt (what the port is teacher-forced along)
Names: O<i> Original pass 0, Ob<i> Original pass 1 (when it differs), and <tag><i> for every --port-log NAME=FILE
(the tag is the part before '='; sequences identical to an earlier one are not written twice).
"""
import json, os, re, sys
def orig_sequences(path):
toks, cur = [], []
for line in open(path):
if line.startswith("T "):
cur.append(int(line.split()[1]))
elif line.startswith("DONE"):
toks.append(cur); cur = []
return toks
def prompts(path):
out = []
for line in open(path):
m = re.match(r"GEN \d+ ([0-9,]+)\s*$", line)
if m: out.append([int(x) for x in m[1].split(",")])
return out[::2] # every prompt is requested twice (two passes)
def port_sequences(path, arm=None):
"""Pass-0 outputs of the port's corpus log; with ARM only the section after '=== arm ARM:' (job 805 style logs)."""
seqs = {}
inside = arm is None
for line in open(path, errors="replace"):
if arm is not None and line.startswith("=== arm "):
inside = line.startswith(f"=== arm {arm}:")
if not inside: continue
m = re.match(r"DBG corpus (\d+) output \((\d+) tokens, rounds \d+\): ([0-9 ]+)", line)
if m: seqs[int(m[1])] = [int(x) for x in m[3].split()]
return seqs
def main(argv):
out = argv[0]; opts = argv[1:]
orig = os.path.expanduser("~/work/gpu-runs/round-profile/orig-ph/out.txt")
reqs = os.path.expanduser("~/work/gpu-runs/round-profile/original-requests.txt")
ports, frees = [], []
i = 0
while i < len(opts):
if opts[i] == "--orig-out": orig = opts[i + 1]; i += 2
elif opts[i] == "--requests": reqs = opts[i + 1]; i += 2
elif opts[i] == "--free-run": tag, f = opts[i + 1].split("=", 1); frees.append((tag, f)); i += 2
elif opts[i] == "--port-log": tag, f = opts[i + 1].split("=", 1); ports.append((tag, f)); i += 2
else: raise SystemExit("bad option " + opts[i])
os.makedirs(out + "/cases", exist_ok=True); os.makedirs(out + "/force", exist_ok=True)
P = prompts(reqs); O = orig_sequences(orig)
assert len(P) == 6 and len(O) == 12, (len(P), len(O))
meta, seen = {}, {}
def add(name, prompt_index, prompt, tokens, source):
key = tuple(prompt + tokens)
if key in seen:
return
seen[key] = name
open(f"{out}/cases/{name}.ids", "w").write(",".join(map(str, key)))
meta[name] = {"n_prompt": len(prompt), "prompt": prompt_index, "source": source, "n_generated": len(tokens)}
for i, p in enumerate(P):
add(f"O{i}", i, p, O[2 * i], "Original pass 0 (" + orig + ")")
open(f"{out}/force/c{i}.truth", "w").write(",".join(map(str, p + O[2 * i])))
for i, p in enumerate(P):
add(f"Ob{i}", i, p, O[2 * i + 1], "Original pass 1")
for tag, f in ports:
f, _, arm = f.partition("@")
seqs = port_sequences(f, arm or None)
for i, p in enumerate(P):
if i in seqs: add(f"{tag}{i}", i, p, seqs[i], "port " + f)
for tag, run in frees: # the free requests (labels free:<p>:<rep>) of an Original run written by q-common.sh orig_run
names = [n for n in open(run + "/reqs.txt.names").read().split(chr(10)) if n]
seqs = orig_sequences(run + "/out.txt")
for n, toks in zip(names, seqs):
if n.startswith("free:") and n.endswith(":0"):
p = int(n.split(":")[1]); add(f"{tag}{p}", p, P[p], toks, "Original free run " + run)
json.dump(meta, open(out + "/cases/meta.json", "w"), indent=1)
print(sorted(meta), "->", out)
if __name__ == "__main__":
main(sys.argv[1:])