# Qwen4-35B-A3B benchmark, paraloncloud.com, 2026-12-04.
# Usage: URL=http://host:8000/v1/chat/completions python3 concurrency.py
import json,time,urllib.request,statistics,sys
from concurrent.futures import ThreadPoolExecutor
import os
URL=os.environ.get("URL","http://localhost:8000/v1/chat/completions")
def one(i,maxt=600,stream=True):
    body={"model":"Qwen/Qwen4-35B-A3B-FP8","stream":stream,"stream_options":{"include_usage":True},"max_tokens":maxt,"min_tokens":maxt,"ignore_eos":True,
      "messages":[{"role":"user","content":f"[{time.time()}-{i}] Write a long technical note about GPU memory hierarchies."}]}
    t0=time.time()
    r=urllib.request.urlopen(urllib.request.Request(URL,json.dumps(body).encode(),{'Content-Type':'application/json'}),timeout=600)
    first=None; usage=None
    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('usage'): usage=d['usage']
        for c in d.get('choices',[]):
            dl=c.get('delta',{})
            if (dl.get('content') or dl.get('reasoning_content') or dl.get('reasoning')) and first is None: first=time.time()
    t1=time.time(); n=usage['completion_tokens']
    return first-t0, n/(t1-first), n
one(0,50)  # warm
for C in (1,1,1,8,16,32,64,128):
    t=time.time()
    with ThreadPoolExecutor(C) as ex: rs=list(ex.map(one,range(C)))
    wall=time.time()-t; tot=sum(x[2] for x in rs)
    print(f"{C:>3} concurrent: aggregate {tot/wall:6.0f} tok/s | per request median {statistics.median(x[1] for x in rs):4.0f} (min {min(x[1] for x in rs):4.0f}) | TTFT median {statistics.median(x[0] for x in rs):.2f}s max {max(x[0] for x in rs):.2f}s",flush=True)
