File size: 5,341 Bytes
b2882b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()