File size: 6,143 Bytes
a4822b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Resumable, checkpointed async generation against N local vLLM replicas.  A job is {id, prompt, max_tokens, seed}; finished jobs are appended to the jsonl
as they complete and skipped on resume.  Logprob statistics are computed here (no per-token arrays are stored)."""
from __future__ import annotations

import asyncio
import json
import math
import random
import re
import time
from pathlib import Path

import httpx
import numpy as np


def read_ids(path: Path) -> set[str]:
    ids = set()
    if path.exists():
        with open(path) as f:
            for line in f:
                try:
                    ids.add(json.loads(line)["id"])
                except Exception:
                    pass
    return ids


def lp_stats(choice: dict) -> dict:
    lp = ((choice.get("logprobs") or {}).get("content")) or []
    v = np.array([t["logprob"] for t in lp if t.get("logprob") is not None], float)
    if v.size == 0:
        return {}
    out = dict(mean_lp=float(v.mean()), median_lp=float(np.median(v)), p05_lp=float(np.percentile(v, 5)), p25_lp=float(np.percentile(v, 25)), min_lp=float(v.min()),
               mean_lp_tail64=float(v[-64:].mean()), frac_lp_lt_2=float((v < -2).mean()), n_lp=int(v.size))
    tops = [t.get("top_logprobs") for t in lp]
    if tops and tops[0]:
        ent = np.array([-sum(math.exp(c["logprob"]) * c["logprob"] for c in (t or [])) for t in tops])
        out.update(mean_entropy_top5=float(ent.mean()), median_entropy_top5=float(np.median(ent)), p90_entropy_top5=float(np.percentile(ent, 90)), max_entropy_top5=float(ent.max()))
    return out


async def _one(client, base, model, job, p):
    msgs = ([{"role": "system", "content": p["system"]}] if p.get("system") else []) + [{"role": "user", "content": job["prompt"]}]
    body = {"model": model, "messages": msgs, "max_tokens": int(job["max_tokens"]), "temperature": p.get("temperature", 0.0),
            "top_p": p.get("top_p", 1.0), "seed": int(job.get("seed", 0))}
    if p.get("logprobs", True):
        body.update(logprobs=True, top_logprobs=5)
    if p.get("chat_template_kwargs"):
        body["chat_template_kwargs"] = p["chat_template_kwargs"]
    for k in ("top_k", "repetition_penalty", "min_p"):
        if p.get(k) is not None:
            body[k] = p[k]
    t0 = time.time()
    r = await client.post(f"{base}/v1/chat/completions", json=body)
    lat = time.time() - t0
    if r.status_code >= 400:
        raise RuntimeError(f"HTTP {r.status_code}: {r.text[:300]}")
    d = r.json()
    ch = d["choices"][0]
    msg = ch["message"]
    u = d["usage"]
    return {"id": job["id"], "budget": int(job["max_tokens"]), "text": msg.get("content") or "", "reasoning": msg.get("reasoning") or msg.get("reasoning_content"), "finish_reason": ch["finish_reason"],
            "prompt_tokens": u["prompt_tokens"], "completion_tokens": u["completion_tokens"], "latency_s": lat, "t_end": time.time(), "port": base.rsplit(":", 1)[1], **lp_stats(ch)}


async def _run(jobs, out, model, ports, params, per_server, every, stats):
    q: asyncio.Queue = asyncio.Queue()
    for j in jobs:
        q.put_nowait(j)
    t0 = time.time()
    fout, ferr = open(out, "a"), open(str(out) + ".errors", "a")

    async def worker(port, client):
        base = f"http://127.0.0.1:{port}"
        while True:
            try:
                job = q.get_nowait()
            except asyncio.QueueEmpty:
                return
            res, err = None, None
            for attempt in range(8):
                try:
                    res = await _one(client, base, model, job, params)
                    break
                except Exception as e:
                    err = repr(e)[:300]
                    if "maximum context length" in str(e):   # vLLM's "at least N input tokens" is just ctx - requested + 1, so shrink geometrically
                        job = dict(job, max_tokens=max(int(job["max_tokens"] * 0.75), 64))
                        stats["ctx_shrunk"] = stats.get("ctx_shrunk", 0) + 1
                        continue
                    if attempt >= 2:
                        break
                    await asyncio.sleep(2 * (attempt + 1))
            if res is None:
                stats["failed"] += 1
                ferr.write(json.dumps({"id": job["id"], "err": err, "port": port}) + "\n")
                ferr.flush()
                continue
            fout.write(json.dumps(res, ensure_ascii=False) + "\n")
            fout.flush()
            stats["done"] += 1
            stats["completion_tokens"] += res["completion_tokens"]
            stats["prompt_tokens"] += res["prompt_tokens"]
            if stats["done"] % every == 0:
                el = time.time() - t0
                print(f"[{model}] {stats['done']}/{len(jobs)} failed={stats['failed']} {stats['completion_tokens'] / el:.0f} gen tok/s elapsed={el:.0f}s", flush=True)

    limits = httpx.Limits(max_connections=per_server * len(ports) + 8)
    async with httpx.AsyncClient(timeout=httpx.Timeout(7200.0), limits=limits) as client:
        await asyncio.gather(*[worker(p, client) for p in ports for _ in range(per_server)])
    fout.close()
    ferr.close()
    stats["wall_s"] = time.time() - t0


def run_jobs(jobs: list[dict], out: Path, model: str, ports: list[int], params: dict, per_server: int = 128, every: int = 1000, stats: dict | None = None) -> dict:
    out = Path(out)
    out.parent.mkdir(parents=True, exist_ok=True)
    done = read_ids(out)
    todo = [j for j in jobs if j["id"] not in done]
    random.Random(0).shuffle(todo)
    todo.sort(key=lambda j: -j.get("max_tokens", 0))      # longest budgets first (random within a budget class) so long reasoning traces do not form a tail
    stats = stats if stats is not None else {}
    stats.update({"done": 0, "failed": 0, "prompt_tokens": 0, "completion_tokens": 0, "wall_s": 0.0, "n_todo": len(todo), "n_cached": len(jobs) - len(todo), "t_start": time.time()})
    print(f"[{model}] {len(jobs)} jobs, {stats['n_cached']} cached, {len(todo)} to run", flush=True)
    if todo:
        asyncio.run(_run(todo, out, model, ports, params, per_server, every, stats))
    return stats