#!/usr/bin/env bash
# Rocky Tested: AirLLM 70B-class claim test (Qwen2.5-72B-Instruct, bf16 weights), 4 GB GPU cap. Stop other GPU jobs first.
# Baseline: bf16 72B (~145 GB) cannot fully load in 121 GB, so the baseline is ollama Q4_K_M (DIFFERENT PRECISION, different engine).
set -u
D=${WORK:-$PWD}; HUB=${HF_HUB:-$HOME/.cache/huggingface/hub}
OUT=${OUT_DIR:-$D/out70}; mkdir -p "$OUT"; cp "$D/bench.py" "$OUT/"
M=$(ls -d $HUB/models--Qwen--Qwen2.5-72B-Instruct/snapshots/*/ | head -1)
J=$OUT/results.jsonl
{ echo "start $(date -Is)"; free -g; } | tee "$OUT/env.txt"
timeout 170m docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -e USER=bench -e LOGNAME=bench --gpus all --network none --ipc host -e HF_HUB_OFFLINE=1 \
  -v $HUB:$HUB:ro -v $D/shards:/shards -v $OUT:/out rockytest-airllm:fd3bd7e python3 /out/bench.py --mode airllm --model $M --shards /shards/72b --label "72B AirLLM, 4 GB cap" --cap-gb 4 --out /out/results.jsonl
P="Question: What is the capital of France, and what river runs through it? Answer:"
python3 - "$J" "$P" <<"PY"
import json,sys,urllib.request,time
j,p=sys.argv[1],sys.argv[2]
def call(n):
    req=urllib.request.Request("http://localhost:11434/api/generate",data=json.dumps({"model":"qwen2.5:72b-instruct-q4_K_M","prompt":p,"raw":True,"stream":False,"keep_alive":0,"options":{"num_predict":n,"temperature":0,"num_gpu":999}}).encode())
    return json.load(urllib.request.urlopen(req,timeout=1800))
try:
    call(4)  # warm load
    r=call(24)
    rec={"label":"72B normal full load (ollama Q4_K_M, different precision)","mode":"baseline-ollama-q4","ok":True,"new_tokens":r["eval_count"],"gen_seconds":round(r["eval_duration"]/1e9,2),"tokens_per_sec":round(r["eval_count"]/(r["eval_duration"]/1e9),4),"output_text":r["response"],"prompt":p}
except Exception as e:
    rec={"label":"72B ollama Q4 baseline","ok":False,"error":str(e)[:500]}
open(j,"a").write(json.dumps(rec)+"\n"); print(rec)
PY
echo "end $(date -Is)" | tee -a "$OUT/env.txt"; free -g >> "$OUT/env.txt"
cp $J $D/results-70b-latest.jsonl
