File size: 11,616 Bytes
5b238b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/env python3
"""Speed bench for a llama.cpp /v1/chat/completions server.

Two modes:

1. Length sweep - fixed prompts shipped in prompts/prompt_<L>.txt, one request per length.
   Prompts ship as files so every replica sends byte-identical input; sizing them at run
   time against a local tokenizer is what makes "64K" mean different things on different
   servers. They were calibrated for the o200k-harmony vocabulary (gpt-oss family, what the
   measured llama.cpp servers serve). Rebuild with --rebuild-prompts if your tokenizer differs.

2. Dataset - replay a jsonl of ready-made chat samples (datasets):
   2 families x 3 tiers x 10 samples = 60, each carrying its own `messages` payload and the
   `expected_prompt_tokens` it was calibrated to against the server tokenizer.

Rates come from the server's own `timings` block (prompt_per_second / predicted_per_second);
a client-side estimate is used only when the server omits it.

Usage:
  python bench.py http://HOST:PORT MODEL results/out.json --lengths 1024,4096 --runs 2
  python bench.py http://HOST:PORT MODEL results/out.json \
      --dataset datasets/all_samples.jsonl --scale 4k --concurrency 4
  python bench.py --rebuild-prompts openai/gpt-oss-120b
"""
import argparse
import concurrent.futures
import json
import os
import sys
import time
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
PROMPT_DIR = os.path.join(HERE, 'prompts')
DEFAULT_LENGTHS = (1024, 4096, 65536, 131072)
N_CTX = 131072  # context window of the measured deployment
FILLER = (
    'The quarterly report shows that revenue grew across all regions, with the strongest performance in Asia-Pacific. '
    'Engineering shipped the new storage layer, cut p99 latency by 30%, and closed 214 tickets. '
    'Risks include supplier delays, currency exposure, and hiring in the Berlin office. '
)
QUESTION = (
    '\n\nBased on the document above, write a very detailed and comprehensive analysis report of at least 3000 words '
    'covering every point, with sections, risks, recommendations and an action plan. Do not stop early.'
)


def post(url: str, body: dict, timeout: int = 3600):
    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'})
    return urllib.request.urlopen(req, timeout=timeout)


def one_run(url: str, model: str, messages: list, max_tokens: int) -> dict:
    """One cold request; returns the measured rates."""
    body = {
        'model': model,
        'messages': messages,
        'max_tokens': max_tokens,
        'temperature': 0,
        'stream': True,
        'cache_prompt': False,  # true cold prefill - cached prompts would fake the prefill rate
        'stream_options': {'include_usage': True},
        'timings_per_token': True,
        'chat_template_kwargs': {'enable_thinking': False},
        'reasoning_effort': 'low',
    }
    t0 = time.time()
    ttft = None
    n_out = 0
    timings = None
    usage = None
    err = None
    try:
        with post(url + '/v1/chat/completions', body) as r:
            for line in r:
                line = line.decode().strip()
                if not line.startswith('data:') or line == 'data: [DONE]':
                    continue
                d = json.loads(line[5:])
                if d.get('error'):
                    err = 'stream: ' + json.dumps(d['error'])[:300]
                    break
                if d.get('timings'):
                    timings = d['timings']
                if d.get('usage'):
                    usage = d['usage']
                for c in d.get('choices', []):
                    delta = c.get('delta', {})
                    if delta.get('content') or delta.get('reasoning_content'):
                        if ttft is None:
                            ttft = time.time() - t0
                        n_out += 1
    except Exception as e:  # noqa: BLE001 - the point is to record the failure, not to crash the sweep
        err = str(e)[:300]
        try:
            err += ' | ' + e.read().decode()[:300]
        except Exception:
            pass
    total = time.time() - t0
    res = {
        'error': err,
        'wall_s': round(total, 2),
        'ttft_s': round(ttft, 2) if ttft else None,
        'prompt_tokens': (usage or {}).get('prompt_tokens'),
        'completion_tokens': (usage or {}).get('completion_tokens'),
    }
    if timings:  # server-side numbers are authoritative
        res.update(
            prefill_tok_s=round(timings.get('prompt_per_second', 0), 1),
            decode_tok_s=round(timings.get('predicted_per_second', 0), 1),
            prefill_ms=round(timings.get('prompt_ms', 0)),
            decode_ms=round(timings.get('predicted_ms', 0)),
            prompt_n=timings.get('prompt_n'),
            predicted_n=timings.get('predicted_n'),
        )
    elif ttft and usage:
        res.update(
            prefill_tok_s=round(usage['prompt_tokens'] / ttft, 1),
            decode_tok_s=round(usage['completion_tokens'] / max(total - ttft, 1e-3), 1),
        )
    return res


def build_prompt(tokenizer, target: int) -> str:
    """Repeat FILLER until the prompt hits `target` tokens, then append the question."""
    per_block = len(tokenizer.encode(FILLER * 20, add_special_tokens=False)) / 20
    n = max(1, int((target - 40) / per_block))
    prompt = FILLER * n + QUESTION
    while len(tokenizer.encode(prompt, add_special_tokens=False)) > target and n > 1:
        n -= 1
        prompt = FILLER * n + QUESTION
    return prompt


def rebuild_prompts(tokenizer_path: str) -> None:
    from transformers import AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
    os.makedirs(PROMPT_DIR, exist_ok=True)
    for length in DEFAULT_LENGTHS:
        target = min(length, N_CTX - 256)  # leave exactly max_tokens room for the answer
        prompt = build_prompt(tokenizer, target)
        path = os.path.join(PROMPT_DIR, f'prompt_{length}.txt')
        with open(path, 'w') as fh:
            fh.write(prompt)
        print(f'{path}: {len(tokenizer.encode(prompt, add_special_tokens=False))} tokens, {len(prompt)} chars')


def summarise(results: list) -> None:
    """Print mean rates per tier - the number a speed report actually quotes."""
    groups: dict = {}
    for r in results:
        groups.setdefault(r.get('tier', '(all)'), []).append(r)
    print(f"\n{'tier':<10}{'n':>4}{'prefill tok/s':>15}{'decode tok/s':>14}{'TTFT s':>9}{'wall s':>9}{'errors':>8}")
    for tier, rows in sorted(groups.items()):
        ok = [r for r in rows if not r.get('error')]
        if not ok:
            print(f'{tier:<10}{len(rows):>4}{"-":>15}{"-":>14}{"-":>9}{"-":>9}{len(rows):>8}')
            continue
        mean = lambda key: sum(r[key] for r in ok if r.get(key) is not None) / max(  # noqa: E731
            sum(1 for r in ok if r.get(key) is not None), 1)
        print(f'{tier:<10}{len(rows):>4}{mean("prefill_tok_s"):>15.1f}{mean("decode_tok_s"):>14.1f}'
              f'{mean("ttft_s"):>9.1f}{mean("wall_s"):>9.1f}{len(rows) - len(ok):>8}')


def run_length_sweep(a) -> None:
    out = {'mode': 'length_sweep', 'url': a.url, 'model': a.model, 'max_tokens': a.max_tokens,
           'runs': a.runs, 'started': time.strftime('%F %T'), 'results': []}
    for length in (int(x) for x in a.lengths.split(',')):
        path = os.path.join(PROMPT_DIR, f'prompt_{length}.txt')
        with open(path) as fh:
            prompt = fh.read()
        print(f"[{time.strftime('%T')}] len={length} prompt={path} chars={len(prompt)}", flush=True)
        for i in range(a.runs):
            res = one_run(a.url, a.model, [{'role': 'user', 'content': prompt}], a.max_tokens)
            res.update(length=length, tier=f'{length // 1024}k', run=i + 1)
            out['results'].append(res)
            print(f'  run{i + 1}: {json.dumps(res)}', flush=True)
            with open(a.out, 'w') as fh:
                json.dump(out, fh, indent=1)
    finish(out, a)


def run_dataset(a) -> None:
    records = []
    with open(a.dataset) as fh:
        for line in fh:
            r = json.loads(line)
            if a.scale and r.get('scale') != a.scale:
                continue
            if a.family and r.get('task_family') != a.family:
                continue
            records.append(r)
    if a.limit:
        records = records[:a.limit]
    if not records:
        raise SystemExit(f'no records in {a.dataset} matched --scale {a.scale} --family {a.family}')

    out = {'mode': 'dataset', 'url': a.url, 'model': a.model, 'max_tokens': a.max_tokens,
           'dataset': os.path.relpath(a.dataset, HERE), 'concurrency': a.concurrency,
           'started': time.strftime('%F %T'), 'results': []}
    print(f"[{time.strftime('%T')}] {len(records)} samples, concurrency={a.concurrency}, "
          f"max_tokens={a.max_tokens}", flush=True)

    def run_one(rec):
        res = one_run(a.url, a.model, rec['messages'], a.max_tokens)
        res.update(id=rec.get('id'), task_family=rec.get('task_family'), scale=rec.get('scale'),
                   tier=rec.get('scale'), target_tokens=rec.get('target_tokens'),
                   expected_prompt_tokens=rec.get('expected_prompt_tokens'))
        if res.get('prompt_tokens') and rec.get('expected_prompt_tokens'):
            res['prompt_tokens_delta'] = res['prompt_tokens'] - rec['expected_prompt_tokens']
        return res

    with concurrent.futures.ThreadPoolExecutor(max_workers=a.concurrency) as pool:
        futures = {pool.submit(run_one, r): r for r in records}
        for done in concurrent.futures.as_completed(futures):
            res = done.result()
            out['results'].append(res)
            print(f"  {res['id']:<22} in={res.get('prompt_tokens')} out={res.get('completion_tokens')} "
                  f"prefill={res.get('prefill_tok_s')} tok/s decode={res.get('decode_tok_s')} tok/s "
                  f"wall={res.get('wall_s')}s err={res.get('error')}", flush=True)
            with open(a.out, 'w') as fh:
                json.dump(out, fh, indent=1)
    finish(out, a)


def finish(out: dict, a) -> None:
    out['finished'] = time.strftime('%F %T')
    out['results'].sort(key=lambda r: (r.get('tier') or '', r.get('id') or ''))
    with open(a.out, 'w') as fh:
        json.dump(out, fh, indent=1)
    summarise(out['results'])
    print(f'\nDONE -> {a.out}', flush=True)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument('url', nargs='?')
    ap.add_argument('model', nargs='?')
    ap.add_argument('out', nargs='?')
    ap.add_argument('--lengths', default=','.join(str(x) for x in DEFAULT_LENGTHS))
    ap.add_argument('--runs', type=int, default=2)
    ap.add_argument('--max-tokens', type=int, default=256)
    ap.add_argument('--dataset', help='jsonl of ready-made samples (see datasets/)')
    ap.add_argument('--scale', help='dataset mode: only this tier, e.g. 4k')
    ap.add_argument('--family', help='dataset mode: only this family, e.g. code')
    ap.add_argument('--limit', type=int, help='dataset mode: cap the number of samples')
    ap.add_argument('--concurrency', type=int, default=1, help='dataset mode: parallel in-flight requests')
    ap.add_argument('--rebuild-prompts', metavar='TOKENIZER')
    a = ap.parse_args()

    if a.rebuild_prompts:
        rebuild_prompts(a.rebuild_prompts)
        return
    if not (a.url and a.model and a.out):
        ap.error('url, model and out are required (or use --rebuild-prompts)')

    if a.dataset:
        run_dataset(a)
    else:
        run_length_sweep(a)


if __name__ == '__main__':
    sys.exit(main())