File size: 14,599 Bytes
590b382 | 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 | """Rolling Mini TML chats for native same-card A/B. Prepare locally; time only HTTP on the worker."""
from __future__ import annotations
import argparse
import concurrent.futures
import gzip
import hashlib
import json
import statistics
import struct
import time
import urllib.error
import urllib.request
from pathlib import Path
from bench_client import _pct, detect_runaway, load_prompts
TOKENIZER_SHA = '7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6'
CONTEXT = 128 * 1024
CHUNK = 8192
LEVELS = (4, 6)
def ids_digest(ids):
return hashlib.sha256(struct.pack(f'<{len(ids)}I', *ids)).hexdigest()
def check_capacity(card, gauges, plan):
"""Check the loaded service, not the export's preparation pool. This is a lower bound,
not a claim that the scheduler ran every decode simultaneously or hit the prefix cache.
Mini uses one 128-token KV page table with zero draft-page offset; lanes have distinct histories.
"""
tokens = max(plan['targets']) + plan['max_tokens']
lanes = max(int(c) for c in plan['levels'])
pages = gauges['flare_total_kv_pages']
page_size = gauges['flare_kv_page_tokens']
if pages <= 0 or page_size <= 0 or gauges['flare_total_kv_tokens'] != pages * page_size:
raise ValueError(f'Invalid native KV capacity: {gauges}')
required = lanes * ((tokens + page_size - 1) // page_size)
limits = card['flare']
if (card['max_model_len'] < tokens or limits['max_concurrency'] < lanes or pages < required
or limits['prefill_chunk_size'] != plan['chunk']):
raise ValueError(f"{card['id']}: need {lanes} lanes × {tokens} context tokens, "
f"{required} KV pages, chunk {plan['chunk']}; loaded context {card['max_model_len']}, "
f"{limits['max_concurrency']} lanes, {pages} × {page_size}-token pages, "
f"chunk {limits['prefill_chunk_size']}")
return dict(gauges, required_kv_pages=required, required_context=tokens, required_lanes=lanes)
def make_plan(prompts_file, tokenizer_file, *, budget):
from tokenizers import Tokenizer
if hashlib.sha256(tokenizer_file.read_bytes()).hexdigest() != TOKENIZER_SHA:
raise ValueError('Rolling workload needs the pinned Inkling-2-Mini tokenizer')
tok = Tokenizer.from_file(str(tokenizer_file))
tok.encode_special_tokens = True # TML bodies are ordinary text, including control-token spellings.
encode = lambda text: tok.encode(text, add_special_tokens=False).ids
control = lambda name: tok.token_to_id('<|' + name + '|>')
rows = load_prompts(prompts_file)
if len(rows) < max(LEVELS) or len({r['id'] for r in rows}) != len(rows):
raise ValueError('Not enough distinct prompts for simultaneous independent sessions')
if encode(' item' * 3) != encode(' item') * 3 or len(encode(' item')) != 1:
raise ValueError('Unexpected ordinary token padding in pinned tokenizer')
def frame(role, body):
return [control('message_' + ('model' if role == 'assistant' else role)), control('content_text'),
*encode(body), control('end_message')] + ([control('content_model_end_sampling')] if role == 'assistant' else [])
def chat(steps):
# The one leading system frame precedes the TML effort preamble. No BOS or trailing assistant header.
assert steps[0]['role'] == 'system'
return frame('system', steps[0]['content']) + frame('system', 'Thinking effort level: 0') + [
v for s in steps[1:] for v in frame(s['role'], s['content'])]
def msg(role, body):
return {'role': role, 'content': body}
targets = (2 * CHUNK, 8 * CHUNK, CONTEXT - budget - 256, CONTEXT - budget)
levels = {}
for c in LEVELS:
sessions = []
for lane in range(c):
turns, history = [], []
for t, target in enumerate(targets):
case = rows[(lane + t) % len(rows)]
# Insert a frame boundary *after* the large document so the engine can checkpoint it.
# Prior replies are scripted, never a side's generated answer. Both sides get the same input.
delta = ([msg('assistant', 'Recorded.')] if t else
[msg('system', f'Session {c}/{lane}. Use the records as background and answer the final request.')])
delta += [msg('user', ''), msg('assistant', 'Received.'), msg('user', case['prompt'])]
room = target - len(chat(history + delta))
if room < 0:
raise ValueError(f'{case["id"]}: query does not fit the turn increment')
records = ''.join('\nRecord: ' + rows[(lane + t + i) % len(rows)]['prompt'] for i in range(len(rows)))
# Leave a partial final record block as padding. The large part is phase-local prose, not one repeated token.
unit = len(encode(records)); copies = room // (unit + 1)
doc = records * copies
while copies and len(encode(doc)) > room:
copies -= 1; doc = records * copies
delta[-3]['content'] = doc + ' item' * (room - len(encode(doc)))
history += delta
ids = chat(history)
if len(ids) != target:
raise ValueError(f'TML prompt length {len(ids)} != {target}; refusing to estimate token counts')
turns.append(dict(append=delta, prompt_id=case['id'], prompt_tokens=target, prompt_sha256=ids_digest(ids)))
sessions.append(turns)
levels[str(c)] = sessions
return dict(version=1, tokenizer_sha256=TOKENIZER_SHA, source_sha256=hashlib.sha256(prompts_file.read_bytes()).hexdigest(),
max_tokens=budget, chunk=CHUNK, targets=list(targets), levels=levels)
def observe(body, expected, limit):
"""Use raw generated token timestamps on the server's monotonic clock, not HTTP frame counts."""
usage, perf = body['usage'], body['performance']
prompt = usage['prompt_tokens']; ids = body['prompt_token_ids']
cached = usage['prompt_tokens_details']['cached_tokens']
choice, = body['choices']; generated = choice['token_ids']; stamps = choice['token_timestamps_ns']
if (prompt != len(ids) or prompt != expected['prompt_tokens'] or ids_digest(ids) != expected['prompt_sha256']
or not 0 <= cached <= prompt or cached != perf['reused_prompt_tokens'] or cached != body['reused_prompt_tokens']):
raise ValueError('Prompt IDs, metered length or native cache counters disagree')
if (len(stamps) != len(generated) or len(stamps) != usage['completion_tokens'] or not 2 <= len(stamps) <= limit
or not 0 < perf['ingress_ns'] <= perf['enqueue_ns'] <= stamps[0] < stamps[-1]
or any(b < a for a, b in zip(stamps, stamps[1:])) or choice['finish_reason'] not in ('stop', 'length')):
raise ValueError('Missing or inconsistent native decode observation')
m = choice['message']; answer = m.get('content') or ''; text = (m.get('reasoning_content') or '') + answer
return dict(prompt_id=expected['prompt_id'], prompt_sha256=expected['prompt_sha256'], prompt_tokens=prompt,
cached_tokens=cached, uncached_tokens=prompt-cached, completion_tokens=len(stamps),
finish_reason=choice['finish_reason'], output_sha256=ids_digest(generated), has_answer=bool(answer.strip()),
runaway=detect_runaway(text), first_ns=stamps[0], last_ns=stamps[-1],
server_ttft_ms=(stamps[0]-perf['ingress_ns'])/1e6,
decode_tok_s=(len(stamps)-1)*1e9/(stamps[-1]-stamps[0]))
def _request(base_url, model, history, turn, limit, timeout_s):
payload = dict(model=model, messages=history, temperature=0, seed=42, top_p=1, reasoning_effort='none',
max_tokens=limit, stream=False, return_token_ids=True, return_token_timestamps=True)
req = urllib.request.Request(base_url + '/v1/chat/completions', data=json.dumps(payload).encode(),
headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
return observe(json.load(resp), turn, limit)
except urllib.error.HTTPError as exc:
with exc:
raise ValueError(f'HTTP {exc.code}: {exc.read(500).decode(errors="replace")}') from exc
def run_level(base_url, model, plan, c, *, request=_request, timeout_s=240, counters=None, delta=None, leg=None):
sessions = plan['levels'][str(c)]
history = [[] for _ in range(c)]
waves = []
with concurrent.futures.ThreadPoolExecutor(max_workers=c) as ex:
for t, target in enumerate(plan['targets']):
work = []
for lane, turns in enumerate(sessions):
turn = turns[t]; history[lane].extend(turn['append']); work.append((history[lane], turn))
before = counters() if counters else None
start = time.perf_counter()
jobs = [ex.submit(request, base_url, model, h, turn, plan['max_tokens'], timeout_s) for h, turn in work]
rows, errors = [], []
for lane, job in enumerate(jobs):
try:
rows.append(dict(job.result(), lane=lane))
except Exception as exc:
errors.append(dict(lane=lane, error=f'{type(exc).__name__}: {exc}'))
wall = time.perf_counter() - start
# Decode intervals on this *one* server clock reveal scheduler serialization.
peak = active = 0
for _, change in sorted([(r['first_ns'], 1) for r in rows] + [(r['last_ns'], -1) for r in rows]):
active += change
peak = max(peak, active)
waves.append(dict(turn=t, target=target, rows=rows, errors=errors, wall_s=wall,
cached_tokens=[r['cached_tokens'] for r in rows],
peak_overlapping_decodes=peak, flare_metrics=delta(before, counters()) if counters else None,
multi_chunk_requests=sum(r['uncached_tokens'] > plan['chunk'] for r in rows),
ttft_p50_ms=_pct([r['server_ttft_ms'] for r in rows], 50),
ttft_p95_ms=_pct([r['server_ttft_ms'] for r in rows], 95),
decode_tok_s_p50=statistics.median(r['decode_tok_s'] for r in rows) if rows else None,
aggregate_output_tok_s=sum(r['completion_tokens'] for r in rows)/wall if not errors else None))
print('Rolling wave: ' + json.dumps(dict(leg=leg, server=base_url, c=c, **waves[-1]), separators=(',', ':')), flush=True)
if errors:
break # Keep the failed receipt; a shorter or lower-concurrency fallback is not the workload.
return waves
def compare(stock, cand, plan, *, heldout):
problems = []
ratios = {}
for c in LEVELS:
left, right = stock[str(c)], cand[str(c)]
for side, waves in [('Stock', left), ('Candidate', right)]:
if len(waves) != len(plan['targets']) or any(len(w['rows']) != c or w['errors'] for w in waves):
problems.append(f'{side} C={c}: incomplete rolling workload')
continue
if any(r['uncached_tokens'] <= plan['chunk'] for r in waves[0]['rows']):
problems.append(f'{side} C={c}: cold multi-chunk prefill not exercised')
if any(r['cached_tokens'] < plan['chunk'] for r in waves[-1]['rows']):
problems.append(f'{side} C={c}: final follow-up lacks substantial prefix reuse')
if heldout and any(r['finish_reason'] != 'stop' or r['runaway'] or not r['has_answer'] for w in waves for r in w['rows']):
problems.append(f'{side} C={c}: incomplete or runaway held-out answer')
for a, b in zip(left, right):
same_work = len(a['rows']) == len(b['rows']) == c
for s, d in zip(a['rows'], b['rows']):
if (s['lane'], s['prompt_sha256']) != (d['lane'], d['prompt_sha256']):
same_work = False
problems.append(f'C={c} turn {a["turn"]}: different inputs')
if s['cached_tokens'] != d['cached_tokens']:
same_work = False
problems.append(f'C={c} turn {a["turn"]} lane {s["lane"]}: cached tokens '
f'{s["cached_tokens"]} (Stock) != {d["cached_tokens"]} (Candidate)')
if s['output_sha256'] != d['output_sha256']:
same_work = False
problems.append(f'C={c} turn {a["turn"]} lane {s["lane"]}: generated token IDs differ')
# If cache admission differed, report measurements but no equivalent-work speedup.
ratios[f'C{c}_turn{a["turn"]}'] = (dict(
ttft=a['ttft_p50_ms']/b['ttft_p50_ms'], decode=b['decode_tok_s_p50']/a['decode_tok_s_p50'],
aggregate=b['aggregate_output_tok_s']/a['aggregate_output_tok_s']) if same_work else None)
return {'passed': not problems, 'problems': problems, 'matched_work_speedups': ratios}
def repeat_controls(rounds, plan):
"""Describe A1/A2 and B1/B2; never use a noisy control to waive an A/B gate."""
first, second = rounds
expected = {(c, t, lane) for c in LEVELS for t in range(len(plan['targets'])) for lane in range(c)}
def index(waves):
return {(c, w['turn'], row['lane']): row for c in LEVELS for w in waves[str(c)] for row in w['rows']}
controls = {}
for side in ('stock', 'cand'):
a, b = (index(r['rolling_' + side]) for r in (first, second))
keys = expected & a.keys() & b.keys()
controls[side] = dict(expected=len(expected), compared=len(keys), **{
field: sum(a[k][field] == b[k][field] for k in keys)
for field in ('prompt_sha256', 'cached_tokens', 'output_sha256', 'completion_tokens')
})
return controls
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('prompts', type=Path); p.add_argument('tokenizer', type=Path); p.add_argument('out', type=Path)
p.add_argument('--max-tokens', type=int, required=True, choices=(128, 1024))
a = p.parse_args(); plan = make_plan(a.prompts, a.tokenizer, budget=a.max_tokens)
a.out.write_bytes(gzip.compress(json.dumps(plan, separators=(',', ':')).encode(), mtime=0))
print('Rolling plan:', a.prompts.name, 'C=4,6 targets', plan['targets'], 'output limit', a.max_tokens)
|