File size: 9,709 Bytes
197cde1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
"""Regenerate the final assistant turn of HuggingFaceH4/no_robots with Gemma 4 31B-it (vLLM).

Resumable: every finished row is appended to a JSONL file right away, keyed by
(split, row_idx). (prompt_id is NOT unique: two train rows share one, so row_idx
is part of the key.) On restart, rows already in the output file are skipped.

Usage:
  source env.sh   # sets VLLM_API_KEY / VLLM_BASE_URL / VLLM_MODEL (key never printed)
  python generate.py --pilot 50 --out pilot.jsonl
  python generate.py --out generations.jsonl            # full run, both splits
"""
import argparse, asyncio, json, os, random, signal, sys, time
from collections import defaultdict
from datetime import datetime, timezone

from datasets import load_dataset
from openai import AsyncOpenAI, APIConnectionError, APITimeoutError, RateLimitError, InternalServerError

SAMPLING = dict(temperature=1.0, top_p=0.95, top_k=64)  # google/gemma-4-31B-it model card
MAX_TOKENS = 8192
FALLBACK_CONCURRENCY = 8  # used only if the server's --max-num-seqs can't be read


def server_max_num_seqs(port=8001):
    """Read --max-num-seqs from the running vLLM container's launch args (so client concurrency
    always matches the server, even after the user changes it)."""
    import subprocess
    try:
        name = subprocess.run(["docker", "ps", "--filter", f"publish={port}", "--format", "{{.Names}}"],
                              capture_output=True, text=True, timeout=10).stdout.split()[0]
        cmd = json.loads(subprocess.run(["docker", "inspect", name, "--format", "{{json .Config.Cmd}}"],
                                        capture_output=True, text=True, timeout=10).stdout)
        return int(cmd[cmd.index("--max-num-seqs") + 1])
    except Exception:
        return None
SPLITS = ["train", "test"]  # actual split names on the Hub (task.md said train_sft/test_sft)


def build_requests(ds, log):
    reqs = []
    for split in SPLITS:
        for idx, row in enumerate(ds[split]):
            msgs = row["messages"]
            if not msgs or msgs[-1]["role"] != "assistant":
                log(f"SKIP {split}/{idx} prompt_id={row['prompt_id']}: last role is "
                    f"{msgs[-1]['role'] if msgs else 'none'}")
                continue
            context = [{"role": m["role"], "content": m["content"]} for m in msgs[:-1]]
            roles = [m["role"] for m in msgs]
            reqs.append(dict(
                split=split, row_idx=idx, prompt_id=row["prompt_id"], category=row["category"],
                context=context,
                original_response=msgs[-1]["content"],
                is_multiturn=sum(r == "assistant" for r in roles) > 1,
                has_system_prompt=roles[0] == "system",
                # source annotation glitch: context ends with an assistant turn (two assistant turns in a row)
                role_anomaly=bool(context) and context[-1]["role"] != "user",
            ))
    return reqs


def pilot_sample(reqs, n, seed=0):
    rng = random.Random(seed)
    by_cat = defaultdict(list)
    for r in reqs:
        if r["split"] == "train":
            by_cat[r["category"]].append(r)
    cats = sorted(by_cat)
    per = max(1, n // len(cats))
    out = []
    for c in cats:
        out += rng.sample(by_cat[c], per)
    # include one role-anomaly row so its behaviour can be inspected
    anomalies = [r for r in reqs if r["role_anomaly"] and r not in out]
    if anomalies:
        out.append(rng.choice(anomalies))
    return out


async def run(reqs, out_path, progress_path, model, concurrency):
    done = set()
    if os.path.exists(out_path):
        with open(out_path) as f:
            for line in f:
                try:
                    d = json.loads(line)
                    done.add((d["split"], d["row_idx"]))
                except Exception:
                    pass
    todo = [r for r in reqs if (r["split"], r["row_idx"]) not in done]
    prog = open(progress_path, "a", buffering=1)
    fail_log = open(out_path + ".failed.log", "a", buffering=1)

    def log(msg):
        line = f"{datetime.now().isoformat(timespec='seconds')} {msg}"
        prog.write(line + "\n")
        print(line, flush=True)

    log(f"start: {len(reqs)} rows total, {len(done)} already done, {len(todo)} to do, concurrency={concurrency}")
    client = AsyncOpenAI(base_url=os.environ["VLLM_BASE_URL"], api_key=os.environ["VLLM_API_KEY"],
                         timeout=7200, max_retries=0)
    sem = asyncio.Semaphore(concurrency)
    outf = open(out_path, "a", buffering=1)
    stats = dict(rows=0, tokens=0, failed=0)
    t0 = time.time()

    async def one(r):
        async with sem:
            for attempt in range(12):  # ~20 min of patience: survives a vLLM restart
                t = time.time()
                try:
                    resp = await client.chat.completions.create(
                        model=model, messages=r["context"], max_tokens=MAX_TOKENS,
                        temperature=SAMPLING["temperature"], top_p=SAMPLING["top_p"],
                        extra_body=dict(top_k=SAMPLING["top_k"],
                                        chat_template_kwargs={"enable_thinking": False}),
                    )
                    break
                except (APIConnectionError, APITimeoutError, RateLimitError, InternalServerError) as e:
                    wait = min(120, 5 * 2 ** attempt)
                    log(f"retry {r['split']}/{r['row_idx']} attempt {attempt+1}: {type(e).__name__}: {str(e)[:200]} (sleep {wait}s)")
                    await asyncio.sleep(wait)
                except Exception as e:  # non-transient (e.g. 400): fail immediately
                    fail_log.write(json.dumps(dict(split=r["split"], row_idx=r["row_idx"], error=f"{type(e).__name__}: {e}")) + "\n")
                    stats["failed"] += 1
                    return
            else:
                fail_log.write(json.dumps(dict(split=r["split"], row_idx=r["row_idx"], error="retries exhausted")) + "\n")
                stats["failed"] += 1
                return
            c = resp.choices[0]
            msg = c.message
            reasoning = getattr(msg, "reasoning", None) or getattr(msg, "reasoning_content", None) \
                or (msg.model_extra or {}).get("reasoning") or (msg.model_extra or {}).get("reasoning_content")
            rec = {k: r[k] for k in ("split", "row_idx", "prompt_id", "category", "is_multiturn",
                                     "has_system_prompt", "role_anomaly")}
            rec.update(
                gemma_response=msg.content or "",
                reasoning=reasoning,  # should always be None with thinking disabled
                finish_reason=c.finish_reason,
                completion_tokens=resp.usage.completion_tokens,
                prompt_tokens=resp.usage.prompt_tokens,
                served_model=resp.model,
                latency_s=round(time.time() - t, 2),
                generated_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
            )
            outf.write(json.dumps(rec, ensure_ascii=False) + "\n")
            stats["rows"] += 1
            stats["tokens"] += rec["completion_tokens"] or 0

    async def reporter():
        while True:
            await asyncio.sleep(30)
            el = time.time() - t0
            rate = stats["rows"] / el if el else 0
            left = len(todo) - stats["rows"] - stats["failed"]
            eta = left / rate / 3600 if rate else float("nan")
            log(f"progress: {len(done)+stats['rows']}/{len(reqs)} done ({stats['failed']} failed) | "
                f"{stats['tokens']/el:.1f} tok/s | {rate*3600:.0f} rows/h | ETA {eta:.2f} h")

    rep = asyncio.create_task(reporter())
    main_task = asyncio.ensure_future(asyncio.gather(*(one(r) for r in todo)))
    stopped = False

    def on_stop(*_):
        nonlocal stopped
        stopped = True
        log("stop requested (SIGTERM/SIGINT): cancelling in-flight requests; finished rows are kept")
        main_task.cancel()

    loop = asyncio.get_running_loop()
    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, on_stop)
    try:
        await main_task
    except asyncio.CancelledError:
        pass
    rep.cancel()
    el = time.time() - t0
    log(f"{'STOPPED' if stopped else 'finished'}: {stats['rows']} rows, {stats['tokens']} completion tokens in {el:.0f}s "
        f"({stats['tokens']/max(el,1):.1f} tok/s), {stats['failed']} failed")
    return dict(stats, elapsed=el)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="generations.jsonl")
    ap.add_argument("--progress", default=None)
    ap.add_argument("--pilot", type=int, default=0)
    ap.add_argument("--concurrency", type=int, default=None,
                    help="default: the server's --max-num-seqs, read from the vLLM container")
    a = ap.parse_args()
    progress = a.progress or a.out.replace(".jsonl", "") + ".progress.log"
    model = os.environ.get("VLLM_MODEL", "gemma-4-31B-it-fp8-mtp")
    if a.concurrency is None:
        a.concurrency = server_max_num_seqs() or FALLBACK_CONCURRENCY

    ds = load_dataset("HuggingFaceH4/no_robots")
    skip_log = open("skipped_rows.log", "w")
    reqs = build_requests(ds, lambda m: skip_log.write(m + "\n"))
    skip_log.close()
    if a.pilot:
        reqs = pilot_sample(reqs, a.pilot)
    pid_path = a.out + ".pid"
    with open(pid_path, "w") as f:
        f.write(str(os.getpid()))
    try:
        asyncio.run(run(reqs, a.out, progress, model, a.concurrency))
    finally:
        try:
            os.remove(pid_path)
        except FileNotFoundError:
            pass


if __name__ == "__main__":
    main()