feat: reproducibility package — scripts por máquina (runners/gppd-slurm/b200-apptainer/rtx-docker/spark-ollama) com fixes
083e9dc verified | #!/usr/bin/env python3 | |
| """ | |
| Scherm benchmark — Embeddings runner (BGE-M3 e afins). | |
| Mede throughput (embeddings/s) e latência de um modelo de embedding servido | |
| via vLLM (--task embed, endpoint OpenAI /v1/embeddings). Varre concorrência e | |
| tamanho de batch, N repetições, agrega mediana + IQR + percentis. | |
| Mesma filosofia ACM do run_serving.py (seed, env logging, JSON+CSV). | |
| Por que importa pro pitch Scherm: embedding é o coração do RAG (Scherm Assistente). | |
| "Quantos documentos/s essa GPU indexa" é tão decisivo quanto tokens/s de chat. | |
| Uso: | |
| python run_embed.py --served-model BAAI/bge-m3 --base-url http://localhost:8000 \ | |
| --concurrencies 1 8 32 --batch-sizes 1 32 --reps 10 --out /work/results --tag GPU | |
| """ | |
| import argparse, json, os, statistics, time, subprocess, platform, urllib.request | |
| 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} | |
| # Texto jurídico fixo (determinístico) ~ um chunk de RAG típico. | |
| CHUNK=("Trata-se de acao em que se discute a soberania de dados em sistemas de " | |
| "inteligencia artificial operados on-premise por orgaos publicos. O pedido " | |
| "fundamenta-se na necessidade de manter o processamento de informacoes sigilosas " | |
| "dentro do perimetro institucional, sem dependencia de provedores de nuvem " | |
| "estrangeiros, em conformidade com a LGPD e com requisitos de seguranca nacional. ")*3 | |
| def one_request(base_url, model, n_inputs): | |
| body=json.dumps({"model":model,"input":[CHUNK]*n_inputs}).encode() | |
| req=urllib.request.Request(f"{base_url}/v1/embeddings",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 | |
| n=len(d.get("data",[])) | |
| dim=len(d["data"][0]["embedding"]) if n else 0 | |
| return {"latency_s":dt,"n_embed":n,"dim":dim,"ok":True} | |
| except Exception as e: | |
| return {"ok":False,"err":str(e)[:140]} | |
| 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,8,32,64]) | |
| ap.add_argument("--batch-sizes",nargs="+",type=int,default=[1,32]) # inputs por request | |
| ap.add_argument("--reps",type=int,default=10) | |
| ap.add_argument("--warmups",type=int,default=1) | |
| 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) | |
| env={"timestamp_utc":datetime.now(timezone.utc).isoformat(),"modality":"embedding", | |
| "gpu_name":gpu_name(),"nvidia_driver":gpu_driver(),"served_model":a.served_model, | |
| "seed":1234,"reps":a.reps,"chunk_chars":len(CHUNK),"python":platform.python_version()} | |
| safe=a.served_model.replace("/","_"); raw={"env":env,"points":[]}; rows=[] | |
| for bs in a.batch_sizes: | |
| for conc in a.concurrencies: | |
| for _ in range(a.warmups): one_request(a.base_url,a.served_model,bs) | |
| emb_s=[]; lat=[]; vr=[]; dim=0 | |
| 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,bs),range(conc))) | |
| wall=time.time()-t0 | |
| ok=[r for r in res if r.get("ok")] | |
| if ok: | |
| total=sum(r["n_embed"] for r in ok) | |
| emb_s.append(total/wall) # embeddings/s agregado | |
| lat.append(statistics.fmean([r["latency_s"] for r in ok])*1000) # ms | |
| vr.append(vram_used()); dim=ok[0]["dim"] | |
| agg={"embeddings_per_s":quantiles(emb_s),"latency_ms":quantiles(lat),"vram_mib":quantiles(vr)} | |
| raw["points"].append({"batch_size":bs,"concurrency":conc,"dim":dim,"n_ok":len(emb_s),"agg":agg}) | |
| g=lambda k,kk:agg.get(k,{}).get(kk,"") | |
| rows.append([gpu_name(),a.served_model,bs,conc,dim,len(emb_s), | |
| g("embeddings_per_s","median"),g("embeddings_per_s","q3"), | |
| g("latency_ms","median"),g("latency_ms","p95"),g("vram_mib","median")]) | |
| print(f" [EMBED {a.served_model}] bs={bs} conc={conc} dim={dim} n={len(emb_s)} " | |
| f"emb/s(med)={g('embeddings_per_s','median')} lat(med)={g('latency_ms','median')}ms " | |
| f"vram={g('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}/embed_{sfx}_{safe}.json","w") as f: json.dump(raw,f,indent=2) | |
| csv=f"{a.out}/embed_{sfx}_{safe}.csv"; new=not os.path.exists(csv) | |
| with open(csv,"a") as f: | |
| if new: f.write("gpu,model,batch_size,concurrency,dim,n_ok,embeddings_per_s_median,embeddings_per_s_q3,latency_ms_median,latency_ms_p95,vram_mib_median\n") | |
| for r in rows: f.write(",".join(str(x) for x in r)+"\n") | |
| print(f"[OK] embed {a.served_model} -> {a.out} ({csv})",flush=True) | |
| if __name__=="__main__": main() | |