#!/usr/bin/env python3 """ Scherm benchmark — Vision/OCR runner (NuMarkdown, Qwen-VL). Mede latência e throughput de OCR→Markdown em VLM servido via vLLM (endpoint OpenAI chat com image_url). Varre concorrência, N repetições, agrega mediana + IQR + percentis. Mesma filosofia ACM do run_serving.py. Input: uma imagem sintética de documento (gerada localmente, determinística) codificada em base64 — evita dependência de dataset externo no smoke run. Para o artefato final, trocar por página real de documento (com ground truth p/ CER). Uso: python run_vision.py --served-model REPO --base-url http://localhost:8000 \ --concurrencies 1 4 8 --reps 10 --out /work/results --tag GPU """ import argparse, base64, io, json, os, statistics, time, subprocess, platform, urllib.request, urllib.error from datetime import datetime, timezone from concurrent.futures import ThreadPoolExecutor def sh(c): return subprocess.run(c, shell=True, capture_output=True, text=True) def gpu_name(): return (sh("nvidia-smi --query-gpu=name --format=csv,noheader").stdout.strip().splitlines() or ["?"])[0] def gpu_driver(): return (sh("nvidia-smi --query-gpu=driver_version --format=csv,noheader").stdout.strip().splitlines() or [""])[0] def vram_used(): v=[int(x) for x in sh("nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits").stdout.split() if x.strip().isdigit()] return max(v) if v else None def quantiles(xs): xs=sorted(x for x in xs if x is not None) if not xs: return {} n=len(xs) def pct(p): if n==1: return xs[0] k=(n-1)*p; f=int(k); c=min(f+1,n-1); return xs[f]+(xs[c]-xs[f])*(k-f) mean=statistics.fmean(xs); std=statistics.pstdev(xs) if n>1 else 0.0 return {"n":n,"mean":round(mean,3),"std":round(std,3),"median":round(pct(.5),3), "q1":round(pct(.25),3),"q3":round(pct(.75),3),"p95":round(pct(.95),3), "p99":round(pct(.99),3),"min":round(xs[0],3),"max":round(xs[-1],3), "ci95_halfwidth":round(1.96*std/(n**.5),3) if n>1 else 0.0} def make_doc_image(): """Gera imagem de documento determinística (PIL). Fallback: imagem branca.""" try: from PIL import Image, ImageDraw img=Image.new("RGB",(1024,1400),"white"); d=ImageDraw.Draw(img) lines=["TRIBUNAL DE JUSTICA","Processo no 0001234-56.2026","", "DESPACHO","","Vistos. Trata-se de acao em que", "se discute a soberania de dados em", "sistemas de IA on-premise. Defiro o", "pedido. Intimem-se as partes.","", "Tabela de prazos:","Item Prazo Status", "Defesa 15d Pendente","Recurso 10d Aberto","", "Porto Alegre, 29 de maio de 2026."] y=60 for ln in lines: d.text((60,y),ln,fill="black"); y+=42 buf=io.BytesIO(); img.save(buf,format="PNG"); return buf.getvalue() except Exception: # 1x1 branco se não tiver PIL return base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC") def one_request(base_url, model, img_b64, max_tokens): body=json.dumps({"model":model,"max_tokens":max_tokens,"temperature":0,"seed":1234, "messages":[{"role":"user","content":[ {"type":"text","text":"Transcreva este documento para Markdown, preservando a estrutura."}, {"type":"image_url","image_url":{"url":f"data:image/png;base64,{img_b64}"}}]}]}).encode() req=urllib.request.Request(f"{base_url}/v1/chat/completions",data=body, headers={"Content-Type":"application/json"}) t0=time.time() try: with urllib.request.urlopen(req,timeout=300) as r: d=json.load(r) dt=time.time()-t0 toks=d.get("usage",{}).get("completion_tokens",0) return {"latency_s":dt,"out_tokens":toks,"tok_s":(toks/dt if dt>0 else 0),"ok":True} except Exception as e: return {"ok":False,"err":str(e)[:120]} def main(): ap=argparse.ArgumentParser() ap.add_argument("--served-model",required=True) ap.add_argument("--base-url",default="http://localhost:8000") ap.add_argument("--concurrencies",nargs="+",type=int,default=[1,4,8,16]) ap.add_argument("--reps",type=int,default=10) ap.add_argument("--warmups",type=int,default=1) ap.add_argument("--max-tokens",type=int,default=512) ap.add_argument("--out",required=True); ap.add_argument("--tag",default="") ap.add_argument("--run-id",default="") # sufixo único p/ evitar colisão de CSV a=ap.parse_args() os.makedirs(a.out,exist_ok=True) img_b64=base64.b64encode(make_doc_image()).decode() env={"timestamp_utc":datetime.now(timezone.utc).isoformat(),"modality":"vision_ocr", "gpu_name":gpu_name(),"nvidia_driver":gpu_driver(),"served_model":a.served_model, "seed":1234,"reps":a.reps,"max_tokens":a.max_tokens,"python":platform.python_version()} safe=a.served_model.replace("/","_"); raw={"env":env,"points":[]}; rows=[] for conc in a.concurrencies: for _ in range(a.warmups): one_request(a.base_url,a.served_model,img_b64,a.max_tokens) lat=[]; tps=[]; vr=[] for _ in range(a.reps): t0=time.time() with ThreadPoolExecutor(max_workers=conc) as ex: res=list(ex.map(lambda _:one_request(a.base_url,a.served_model,img_b64,a.max_tokens),range(conc))) wall=time.time()-t0 ok=[r for r in res if r.get("ok")] if ok: lat.append(statistics.fmean([r["latency_s"] for r in ok])*1000) # ms tps.append(sum(r["out_tokens"] for r in ok)/wall) # docs throughput proxy: tok/s agregado vr.append(vram_used()) agg={"latency_ms":quantiles(lat),"throughput_tok_s":quantiles(tps),"vram_mib":quantiles(vr)} raw["points"].append({"concurrency":conc,"n_ok":len(lat),"agg":agg}) med=lambda k,kk:agg.get(k,{}).get(kk,"") rows.append([gpu_name(),a.served_model,conc,len(lat),med("latency_ms","median"), med("latency_ms","p95"),med("throughput_tok_s","median"),med("vram_mib","median")]) print(f" [OCR {a.served_model}] conc={conc} n={len(lat)} lat(med)={med('latency_ms','median')}ms " f"tok/s(med)={med('throughput_tok_s','median')} vram={med('vram_mib','median')}MiB",flush=True) sfx=f"{a.tag}_{a.run_id}" if a.run_id else a.tag with open(f"{a.out}/vision_{sfx}_{safe}.json","w") as f: json.dump(raw,f,indent=2) csv=f"{a.out}/vision_{sfx}_{safe}.csv"; new=not os.path.exists(csv) with open(csv,"a") as f: if new: f.write("gpu,model,concurrency,n_ok,latency_ms_median,latency_ms_p95,throughput_tok_s_median,vram_mib_median\n") for r in rows: f.write(",".join(str(x) for x in r)+"\n") print(f"[OK] vision {a.served_model} -> {a.out} ({csv})",flush=True) if __name__=="__main__": main()