quant-vs-api-parity-harness / reference /nmax_depth_bench_reference.sh
Kevletesteur's picture
Upload folder using huggingface_hub
e00f1a7 verified
Raw
History Blame Contribute Delete
10.1 kB
#!/bin/bash
# ⚠️ REFERENCE implementation — tied to a systemd service + launcher on the original
# machine. Adapt <your-launcher>, ports and lock paths to your stack before running.
# N_MAX 2 CONTRE 3 EN PROFONDEUR DE CONTEXTE — 2026-08-09. La piste ouverte du §20.4.
#
# CE QU'ON SAIT DEJA (ne pas le remesurer) :
# - a contexte ~nul, n3 bat n2 : 24,33 vs 21,97 (04/08) et 21,63 vs 19,74 (05/08).
# - MAIS l'optimum n_max=3 a ete etabli a contexte nul, et en production (~150k) la longueur
# moyenne acceptee tombe de 3,05 a ~2,3 ⟹ « l'optimum se deplace probablement vers
# n_max = 2 » (§20.4, jamais mesure). Corroboration externe du 09/08 : le repo HF
# singulared (bench sur gfx1151 Strix Halo, notre matos) trouve n_max=2 optimal.
# - le gain DSpark depend de la FAMILLE (+101 % toolcall vs +46 % physique, §16h)
# ⟹ on mesure DEUX familles, pas une.
#
# PROTOCOLE (lecons de la campagne) :
# - lanceur <your-launcher> tel quel (DS4_NMAX), env de prod GGML_CUDA_DISABLE_GRAPHS=1
# + LLAMA_NO_FUSE_HC_POST=1 — aucun ecart de flags possible.
# - port 8129 : hermes ne peut pas polluer les mesures avec une requete Telegram.
# - ds4-cache auto-save AVANT d'arreter la prod (le slot Nyx survit au banc).
# - prompts EMBOITES par famille (16k commence par 2k) + cache_prompt ⟹ prefill paye 1 fois.
# - chauffe 256 tokens non comptee au chargement, run 1 de chaque palier exclu au
# depouillement (il paie le prefill ET la chauffe du palier).
# - draft_n / draft_n_accepted lus AUX DEUX niveaux du JSON (racine ET timings) : le zero
# du §20.4 venait tres probablement d'une lecture a la racine seule.
# - t/s ET ms/eval : un ecart de t/s sans acceptation constante ne dit rien de la machine.
set -u
exec 9>/tmp/bancnmaxprof.lock; flock -n 9 || { echo "deja en cours"; exit 1; }
exec 8>/tmp/ds4_gpu.lock
flock -w 14400 8 || { echo "machine occupee — abandon"; exit 1; }
echo " [verrou GPU obtenu]" >&2
D=.
OUT="$D/nmax_profondeur.tsv"
PORT=8129
printf "nmax\tfamille\tcontexte\trun\tgen_tps\tpredicted_ms\tpredicted_n\tdraft_n\tdraft_acc\tms_par_eval\tprefill_ms\n" > "$OUT"
# etat du build — lecon de la variable qui a fui
grep -n "CMAKE_HIP_FLAGS:STRING" /root/llama-upstream/build-rocm/CMakeCache.txt 2>/dev/null | sed 's/^/ /' >&2
sha256sum ${LLAMA_BIN:-.}/libggml-hip.so 2>/dev/null | cut -c1-16 | sed 's/^/ libggml-hip: /' >&2
DS4_ACTIF=0; systemctl is-active --quiet ds4 && DS4_ACTIF=1
remettre() {
pkill -f "lla""ma-server.*--port $PORT" 2>/dev/null; sleep 3
[ "$DS4_ACTIF" = "1" ] && { echo "→ remise en service de ds4" >&2; systemctl start ds4 2>/dev/null; }
}
trap remettre EXIT INT TERM
if [ "$DS4_ACTIF" = "1" ]; then
<your-slot-cache-tool> auto-save 2>&1 | sed 's/^/ /' >&2 || true
systemctl stop ds4; sleep 5
fi
attendre_gtt() { for i in $(seq 1 90); do u=$(cat /sys/class/drm/card0/device/mem_info_gtt_used 2>/dev/null); [ -z "$u" ] && return; [ "$u" -lt 2147483648 ] && return; sleep 2; done; }
# ── prompts emboites, 2 familles x {2000, 16000} ──
python3 - <<'PY'
import json
mots = ("lattice gauge theory confinement Wilson loop plaquette holonomy Polyakov center "
"vortex string tension glueball spectrum renormalization coupling beta function "
"asymptotic freedom instanton topological charge cooling Balaban block spin "
"cluster expansion polymer activity Mayer graph Gribov horizon Faddeev Popov").split()
q_phys = (" Derive the one-loop beta function of SU(N) Yang-Mills theory in detail. Give the "
"gluon self-energy, the ghost contribution, the vertex renormalization, explain why "
"the sign is negative, and derive the coefficient b0 step by step.")
fichiers = ("wilson polyakov creutz luscher symanzik kogut susskind osterwalder seiler frohlich "
"glimm jaffe brydges federbush battle magnen rivasseau feldman knorrer trubowitz "
"hurd imbrie spencer aizenman duminil").split()
appel = '{"name":"read_file","arguments":{"path":"/root/physique/notes/%s.md","offset":%d,"limit":200}}'
q_tool = ('\nGenere les 25 appels suivants sur exactement le meme modele, pour les fichiers : '
+ ', '.join(f + '.md' for f in fichiers) +
'. Uniquement le JSON, une ligne par appel, aucun commentaire.')
for fam in ('physique', 'toolcall'):
base, prev = "", 0
for n in (2000, 16000):
if fam == 'physique':
base += ' ' + ' '.join(mots[(i * 13) % len(mots)] for i in range(prev, int(n / 1.25)))
prev = int(n / 1.25)
prompt = "<|User|>" + base.strip() + q_phys + "<|Assistant|>"
else:
lignes = [appel % (fichiers[i % len(fichiers)], 200 * i) for i in range(prev, int(n / 30))]
base += '\n' + '\n'.join(lignes)
prev = int(n / 30)
prompt = "<|User|>Voici des appels d'outils deja effectues :" + base + q_tool + "<|Assistant|>"
json.dump({"prompt": prompt, "n_predict": 250, "temperature": 1.0, "top_p": 0.95,
"min_p": 0.0, "seed": 42, "cache_prompt": True},
open(f'/tmp/np_{fam}_{n}.json', 'w'))
print(" prompts emboites ecrits (physique+toolcall x {2000,16000})")
PY
mesurer() { # $1=nmax $2=famille $3=palier
local nm="$1" fam="$2" n="$3" r
echo " --- n_max=$nm $fam ~${n} tokens ---" >&2
for r in 1 2 3 4; do
rm -f /tmp/np_out.json
curl -s --max-time 3600 "http://127.0.0.1:$PORT/completion" \
-H "Content-Type: application/json" -d @/tmp/np_${fam}_${n}.json > /tmp/np_out.json 2>/dev/null
python3 - "$nm" "$fam" "$n" "$r" "$OUT" /tmp/np_out.json <<'PY'
import json, sys
nm, fam, n, r, out, f = sys.argv[1:7]
try:
d = json.load(open(f))
except Exception:
open(out, 'a').write(f"{nm}\t{fam}\t{n}\t{r}\tILLISIBLE\t-\t-\t-\t-\t-\t-\n"); raise SystemExit
t = d.get('timings', {})
pn = t.get('predicted_n', 0) or 0
pms = t.get('predicted_ms', 0.0) or 0.0
tps = t.get('predicted_per_second', 0.0) or 0.0
prf = t.get('prompt_ms', 0.0) or 0.0
# les champs draft ont deux adresses selon les versions : timings d'abord, racine ensuite
dn = t.get('draft_n') or d.get('draft_n') or 0
da = t.get('draft_n_accepted') or d.get('draft_n_accepted') or 0
ev = pn - da
mse = pms / ev if ev > 0 else 0.0
open(out, 'a').write(f"{nm}\t{fam}\t{n}\t{r}\t{tps:.2f}\t{pms:.0f}\t{pn}\t{dn}\t{da}\t{mse:.1f}\t{prf:.0f}\n")
print(f" run {r}: {tps:6.2f} t/s | accepte {da}/{dn} | {mse:6.1f} ms/eval | prefill {prf/1000:.1f} s",
file=sys.stderr)
PY
done
}
for NM in 3 2; do
echo "=== CONFIG n_max=$NM ===" >&2
attendre_gtt
env GGML_CUDA_DISABLE_GRAPHS=1 LLAMA_NO_FUSE_HC_POST=1 DS4_NMAX=$NM DS4_PORT=$PORT \
setsid nohup <your-launcher> > "$D/np_srv_n$NM.log" 2>&1 < /dev/null 8>&- 9>&- &
ok=0
for i in $(seq 1 150); do
[ "$(curl -s -o /dev/null -w '%{http_code}' -m 5 http://127.0.0.1:$PORT/health 2>/dev/null)" = "200" ] && { ok=1; break; }
ps -eo cmd | grep -q "llama-serve[r].*--port $PORT" || break
sleep 5
done
[ $ok -ne 1 ] && { echo "STOP: serveur n_max=$NM non demarre"; tail -12 "$D/np_srv_n$NM.log"; exit 1; }
echo " serveur n_max=$NM pret" >&2
# chauffe non comptee (le 1er run apres chargement est 25-30 % plus lent)
rm -f /tmp/np_w.json
curl -s --max-time 900 "http://127.0.0.1:$PORT/completion" -H "Content-Type: application/json" \
-d '{"prompt":"<|User|>Explique brievement le confinement.<|Assistant|>","n_predict":256,"temperature":0.0,"cache_prompt":false}' \
> /tmp/np_w.json 2>/dev/null
for fam in physique toolcall; do
for n in 2000 16000; do mesurer $NM $fam $n; done
done
pkill -f "lla""ma-server.*--port $PORT" 2>/dev/null
sleep 8
for i in $(seq 1 20); do ss -ltn 2>/dev/null | grep -q ":$PORT " || break; sleep 2; done
done
echo >&2
column -t -s$'\t' "$OUT" >&2
python3 - "$OUT" <<'PY'
import sys, collections, statistics
cle = collections.defaultdict(lambda: {'tps': [], 'mse': [], 'acc': []})
for l in list(open(sys.argv[1]))[1:]:
r = l.rstrip('\n').split('\t')
if len(r) < 10 or r[4] == 'ILLISIBLE' or r[3] == '1': # run 1 = chauffe du palier
continue
try:
k = (r[0], r[1], int(r[2]))
cle[k]['tps'].append(float(r[4]))
if float(r[9]) > 0: cle[k]['mse'].append(float(r[9]))
dn, da = int(r[7]), int(r[8])
if dn > 0: cle[k]['acc'].append(da / dn)
except ValueError:
pass
print("\n ══ N_MAX 2 vs 3 EN PROFONDEUR (mediane des runs 2-4) ══\n")
print(f" {'famille':9s} {'ctx':>6s} {'n3 t/s':>8s} {'n2 t/s':>8s} {'delta':>7s}"
f" {'n3 acc':>7s} {'n2 acc':>7s} {'n3 ms/ev':>9s} {'n2 ms/ev':>9s}")
print(" " + "-" * 72)
for fam in ('physique', 'toolcall'):
for n in (2000, 16000):
a, b = cle.get(('3', fam, n)), cle.get(('2', fam, n))
if not a or not b or not a['tps'] or not b['tps']:
print(f" {fam:9s} {n:6d} donnees incompletes"); continue
t3, t2 = statistics.median(a['tps']), statistics.median(b['tps'])
e3 = 100 * (max(a['tps']) - min(a['tps'])) / t3
e2 = 100 * (max(b['tps']) - min(b['tps'])) / t2
ac3 = 100 * statistics.mean(a['acc']) if a['acc'] else float('nan')
ac2 = 100 * statistics.mean(b['acc']) if b['acc'] else float('nan')
m3 = statistics.median(a['mse']) if a['mse'] else float('nan')
m2 = statistics.median(b['mse']) if b['mse'] else float('nan')
g = 100 * (t2 / t3 - 1)
sig = '' if abs(g) > max(e3, e2) else ' ~' # ecart sous la dispersion = rien
print(f" {fam:9s} {n:6d} {t3:8.2f} {t2:8.2f} {g:+6.1f}%{sig}"
f" {ac3:6.1f}% {ac2:6.1f}% {m3:9.1f} {m2:9.1f}")
print("\n ~ = ecart plus petit que l'etendue des runs ⟹ non significatif.")
print(" Lecture : si n2 gagne seulement la ou l'acceptation n3 est basse (physique profond),")
print(" c'est le mecanisme du §20.4 ; si n2 perd partout, l'optimum n_max=3 tient aussi en")
print(" profondeur et la reco singulared ne s'applique pas a notre config.")
PY
echo "BANC_NMAX_PROFONDEUR_FINI"