JonesLin's picture
Switch teacher outputs to one JSON file per batch; add queue helper and option keys
b2882b8 verified
Raw History Blame Contribute Delete
5.34 kB
"""Batch queue for the teacher run: hands out batches and checks output format. Never sees answers.
Run from the pack root (the folder holding tasks/ and outputs/):
python3 tasks/queue.py next N [--first A --last B] claim up to N unstarted batches, print their names
python3 tasks/queue.py check NAME check outputs/NAME.json; if bad, delete it and requeue
python3 tasks/queue.py status [--first A --last B] counts
python3 tasks/queue.py release requeue claimed batches with no valid output
(only when no worker is running, e.g. after a restart)
A batch that fails the check 3 times is given up (listed in progress/failed.txt).
"""
import argparse
import fcntl
import json
from pathlib import Path
BATCHES, OUTPUTS, PROGRESS = Path("tasks/batches"), Path("outputs"), Path("progress")
CLAIMED, BAD, FAILED = PROGRESS / "claimed.txt", PROGRESS / "bad.txt", PROGRESS / "failed.txt"
MAX_TRIES = 3
def names(path):
return path.read_text().split() if path.is_file() else []
def append(path, name):
with path.open("a") as stream:
stream.write(name + "\n")
def problem(name):
"""None if outputs/NAME.json answers batch NAME in the right format, else the reason."""
items = [json.loads(line) for line in (BATCHES / f"{name}.jsonl").read_text(encoding="utf-8").splitlines()]
path = OUTPUTS / f"{name}.json"
if not path.is_file():
return "no output file"
try:
rows = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError) as error:
return f"not valid JSON ({error})"
if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):
return "not a JSON array of objects"
by_id = {row.get("id"): row for row in rows}
if len(rows) != len(items) or set(by_id) != {item["id"] for item in items}:
return f"ids differ from the batch (need each of its {len(items)} ids once)"
for item in items:
row = by_id[item["id"]]
if not isinstance(row.get("reasoning"), str) or not row["reasoning"].strip():
return f"empty reasoning for {item['id']}"
if row.get("answer") not in item["options"]:
return f"answer for {item['id']} is not one of its option keys"
if len({row["reasoning"].strip() for row in rows}) < len(rows):
return "same reasoning text for different items"
return None
def in_range(first, last):
found = sorted(path.stem for path in BATCHES.glob("batch-*.jsonl"))
return [name for name in found if first <= int(name.split("-")[1]) <= last]
def run(args):
claimed, failed = names(CLAIMED), set(names(FAILED))
if args.command == "next":
taken = set(claimed)
picked = [name for name in in_range(args.first, args.last)
if name not in taken and not (OUTPUTS / f"{name}.json").is_file()][:int(args.name)]
for name in picked:
append(CLAIMED, name)
print("\n".join(picked) if picked else "none left")
elif args.command == "check":
reason = problem(args.name)
if reason is None:
print(f"ok {args.name}")
return
(OUTPUTS / f"{args.name}.json").unlink(missing_ok=True)
append(BAD, args.name)
if names(BAD).count(args.name) >= MAX_TRIES:
append(FAILED, args.name) # stays claimed, so it is not handed out again
print(f"bad {args.name}: {reason}; given up after {MAX_TRIES} tries")
else:
CLAIMED.write_text("".join(name + "\n" for name in claimed if name != args.name))
print(f"bad {args.name}: {reason}; requeued")
elif args.command == "status":
batches, taken = in_range(args.first, args.last), set(claimed)
done = {name for name in batches if (OUTPUTS / f"{name}.json").is_file()}
print(json.dumps({"batches": len(batches), "done": len(done),
"failed": sum(name in failed for name in batches),
"running": sum(name in taken and name not in failed | done for name in batches),
"not_started": sum(name not in taken | done for name in batches)}))
elif args.command == "release":
keep = []
for name in claimed:
if name in failed or problem(name) is None:
keep.append(name)
else:
(OUTPUTS / f"{name}.json").unlink(missing_ok=True)
CLAIMED.write_text("".join(name + "\n" for name in keep))
print(f"released {len(claimed) - len(keep)}")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("command", choices=["next", "check", "status", "release"])
parser.add_argument("name", nargs="?", help="N for next, batch name for check")
parser.add_argument("--first", type=int, default=0)
parser.add_argument("--last", type=int, default=10**9)
args = parser.parse_args()
PROGRESS.mkdir(exist_ok=True)
OUTPUTS.mkdir(exist_ok=True)
with open(PROGRESS / ".lock", "w") as lock: # parallel calls would race on claimed.txt
fcntl.flock(lock, fcntl.LOCK_EX)
run(args)
if __name__ == "__main__":
main()