Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions tools/rdna3-w2/rocm-runtime-knobs/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
rocm-runtime-knobs: verified ROCm runtime knob list, A/B script, launch-gap microbench (prep task, no llama.cpp code)

Why: every dependent kernel launch costs ~2 us idle on this ROCm (one AQL packet with barrier + acquire/release). Measured idle per token:
Nemotron 1.7 ms of 9.6, Gemma 3.0 of 26.8, Qwen3.8 2.5 of 27; Nemotron-DFlash GPU idle 45% (392 launches per generated token).
GGML_CUDA_GRAPH_OPT=1 made it worse; HSA_ENABLE_INTERRUPT / ROC_ACTIVE_WAIT_TIMEOUT / GGML_CUDA_DISABLE_GRAPHS: no effect.
These scripts find out whether any CLR/HSA runtime knob of the library that is really in the image moves it.

FILES (build-bins/w2/rocm-runtime-knobs/, mirrored on branch opt/w2-rocm-runtime-knobs under tools/rdna3-w2/rocm-runtime-knobs/)
knobs.txt names found with strings in libamdhip64.so + libhsa-runtime64.so of rdna3-build:local (ROCm 7.16.26385 / core-10.1),
plus a second grep for ^DEBUG_(HIP|OCL)_ (the graph knobs live there). NAMES ONLY: strings cannot show defaults or meaning.
ab.sh whole-card A/B of the knobs (below)
ab-stats.py the statistics (pure python, also used for the table)
../../tools/launchgap/{launchgap.hip,build.sh,sweep.sh} per-launch idle microbench (copy on the branch: launchgap/)

INVENTORY RESULT
All 14 knob names of the task exist: HIP_FORCE_DEV_KERNARG, DEBUG_CLR_AQL_BARRIER_OPT, DEBUG_CLR_DIRECT_DOORBELL, DEBUG_CLR_DOORBELL_SKIP,
ROC_USE_FGS_KERNARG, DEBUG_CLR_BLIT_KERNARG_OPT, ROC_SKIP_KERNEL_ARG_COPY, GPU_USE_DEVICE_QUEUE, ROC_AQL_QUEUE_SIZE,
DEBUG_CLR_BATCH_CPU_SYNC_SIZE, DEBUG_CLR_MAX_BATCH_SIZE, ROC_SYSTEM_SCOPE_SIGNAL, ROC_CPU_WAIT_FOR_SIGNAL, GPU_MAX_HW_QUEUES.
DEBUG_CLR_GRAPH_PACKET_CAPTURE does NOT exist (as expected). ab.sh still skips any name that is not in knobs.txt.
Extras found, added to ab.sh (guessed values; NO_EXTRAS=1 drops them): DEBUG_CLR_AQL_DEV_QUEUE=1, AMD_DIRECT_DISPATCH=1,
DEBUG_HIP_GRAPH_CLASSIC_PATH=1. Present but NOT tried (value semantics unknown, would be guesses): DEBUG_HIP_GRAPH_BATCH_SIZE,
DEBUG_HIP_FORCE_GRAPH_QUEUES, DEBUG_HIP_GRAPH_SEGMENT_SCHEDULING, DEBUG_HIP_GRAPH_MIN_OVERLAP, DEBUG_HIP_DYNAMIC_QUEUES,
DEBUG_CLR_USE_MOVDIR64B, GPU_STREAMOPS_CP_WAIT, HSA_ENABLE_MWAITX, HSA_KERNARG_POOL_SIZE, ROC_SIGNAL_POOL_SIZE.
Try them by hand: KNOBS="DEBUG_HIP_GRAPH_BATCH_SIZE=16" ... bash ab.sh (names are checked against knobs.txt).

TWO DEVIATIONS FROM THE PLAN (both on purpose)
1. "GPURUN_OPTS='-e HIP_FORCE_DEV_KERNARG=0' overrides the hardcoded =1" is wrong: gpurun.sh puts ${GPURUN_OPTS} BEFORE its own
'-e HIP_FORCE_DEV_KERNARG=1', and docker takes the last -e, so the control would silently run as =1. gpurun.sh's own '-e K=V'
argument comes after and wins. ab.sh therefore calls gpurun.sh -e directly (not lb.sh, which cannot pass -e) and builds the same
llama-bench command as lb.sh (-lm dio -ngl 99 -fa on ... -p 0 -n 128 -r 5). Use 'gpurun.sh -e', not GPURUN_OPTS, for this knob.
2. One block, but not every knob on every model: ~25 knob variants x 4 models x 2 runs (with the interleaved baselines) is ~3 h.
ab.sh screens all knobs on Nemotron (most launch bound, loads in seconds), then confirms only the survivors on all four models.
CONFIRM_ALL=1 gives the full matrix.

RUN ORDER (GPU window; run the build first, it is CPU only)
R=/home/tom/docker/projects/llama.cpp-RDNA3; K=$R/build-bins/kern; cd $K; B0=$R/build-bins/w2/base-build/bin
0. (before the window, CPU) $R/build-bins/tools/launchgap/build.sh # hipcc, gfx1100, nothing is run
1. launchgap, direct measurement of the idle per launch, whole card:
BLOCK_TIMEOUT=1800 ./gpublock.sh bash $R/build-bins/tools/launchgap/sweep.sh # ~10 min, baseline + every knob
or one knob (plan command; gpusmall does not unload the router, so numbers next to a busy production are noisy):
./gpusmall.sh $K/gpurun.sh -n kern-launchgap $R/build-bins/tools/launchgap/launchgap 2000
./gpusmall.sh $K/gpurun.sh -n kern-launchgap -e KNOB=V $R/build-bins/tools/launchgap/launchgap 2000
Read the 'stream' rows: 'gap med' = idle between kernel i and i+1 measured on the GPU with wall_clock64; 'host' = CPU enqueue cost;
'graph' rows = the same N launches replayed from a hipGraph. A knob that does not move 'gap med' of tiny/full/bigarg stream rows
(and the graph rows) cannot move tg; skip it in step 2 with KNOBS=... .
2. A/B of tg128, whole card (~1 h; the default gpublock timeout of 2400 s is too short):
BLOCK_TIMEOUT=9000 ./gpublock.sh bash $R/build-bins/w2/rocm-runtime-knobs/ab.sh $B0
$B0 must hold llama-bench AND llama-server (base-build has both). Results: build-bins/w2/rocm-runtime-knobs/results/<date>/
(runs.jsonl, summary.txt). Phases: screen on Nemotron -> confirm survivors on Nemotron, Gemma, Qwen3.8, Qwen4 -> combination of the
winners (best value per name, at most 5) -> greedy hash on Nemotron DFlash (specbench --modes greedy --n 128, preset
nemotron-3.5-bolt-e4b-dflash with parallel 1, ctx 16384, no mmproj; base twice to prove determinism, then every winner and the combo).
Models that are not ready are skipped (Qwen4 while its download is incomplete or *.incomplete exists).
Tuning env: MODELS="nem gem" REPS=5 SCREEN_MIN_PCT=0.5 CONFIRM_MAX=6 MIN_PCT=1.0 KNOBS="K=V ..." NO_EXTRAS=1 SKIP_HASH=1 RUN_TIMEOUT=600.
Dry run (prints the commands, runs nothing, no GPU, no lock): DRYRUN=1 OUT=/tmp/x bash ab.sh /any/dir
3. Greedy hash by hand for one knob (also usable for the tg of the real DFlash path):
python3 -I $R/build-bins/tools/bench/specbench.py t $B0 --n 128 --modes greedy -- <args of the nemotron-dflash preset>
with SB_ENV=K=V (single knob; the only route that can override HIP_FORCE_DEV_KERNARG) or GPURUN_OPTS='-e K=V -e K2=V2'.

EXPECTED RUNTIME: launchgap sweep ~10 min, ab.sh ~1 h (screen ~20 min, confirm 25-40 min depending on survivors, combo + hash ~10 min).
A GPU hang or a debug-knob stall costs at most one run timeout (600 s, container removed); two failed baselines in a row abort the script.

DECISION RULE
A knob (or the combination) is a candidate only if ALL hold:
- tg128 gain > 1% AND > the run-to-run spread (ab-stats.py: the larger of the drift between the two bracketing baselines and
2*stdev/sqrt(n) of the 5 samples; each knob run is compared with the mean of the baseline right before and after it),
- it wins on at least one model and does not lose (beyond the same threshold) on any other, no failed or timed-out run,
- the greedy text hashes of the Nemotron-DFlash run are IDENTICAL to the baseline (and the baseline is deterministic).
A knob that moves launchgap 'gap med' but not tg is not worth it. Multi-model gains of 1-3% are the realistic ceiling
(about 1.4 ms/token of ~2.5-3 ms idle on Gemma at best).
DEBUG_CLR_* are debug flags: they can hang or corrupt; that is what the timeout and the hash are for.
A winning knob goes into production ONLY with the user approval (it would be an env line in the router preset or the image).
Nothing here touches prodimg/Dockerfile, router-config.ini, docker compose or any llama-cpp-rocm:* image.
131 changes: 131 additions & 0 deletions tools/rdna3-w2/rocm-runtime-knobs/ab-stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""ab-stats.py <runs.jsonl> <cmd> [args] statistics for ab.sh (pure python, no GPU).

runs.jsonl: one JSON object per llama-bench run, in execution order:
{"seq": n, "phase": "screen|confirm|combo", "model": "nem|gem|q38|q4", "label": "base" or "K=V[ K2=V2]", "rc": 0,
"median": t/s, "mean": t/s, "stdev": t/s, "samples": [..]}
A knob run is compared to the mean of the nearest base run before it and the nearest base run after it (same phase and model),
i.e. the thermal / clock drift is cancelled by the bracket.
delta_pct = 100 * (knob - ref) / ref
spread_pct = max(100 * |base_before - base_after| / ref, 2 * 100 * stdev_knob / sqrt(n) / ref) (run-to-run noise estimate)
WIN : delta_pct > max(MIN_PCT, spread_pct) LOSS: delta_pct < -max(MIN_PCT, spread_pct) (MIN_PCT default 1.0)

cmds:
table [phase] per run delta table
screen <min_pct> [top] knobs (labels) whose screen delta is >= min_pct (positive only), best first, at most top, one per line
winners confirm phase: per knob name the best value that wins on >= 1 model and loses on none; prints
'K=V K2=V2' (one line, empty if none)
combo combo phase table + verdict line
"""
import json, math, os, sys

MIN_PCT = float(os.environ.get('MIN_PCT', '1.0'))


def load(path):
rows = []
if os.path.exists(path):
for l in open(path):
l = l.strip()
if l.startswith('{'):
rows.append(json.loads(l))
return rows


def ok(r):
return r.get('rc') == 0 and r.get('median') is not None


def compare(rows, phase=None):
"""-> list of dicts for every knob run with a valid reference"""
out = []
groups = {}
for r in rows:
if phase and r['phase'] != phase:
continue
groups.setdefault((r['phase'], r['model']), []).append(r)
for (ph, model), g in groups.items():
g.sort(key=lambda r: r['seq'])
for i, r in enumerate(g):
if r['label'] == 'base':
continue
before = next((b for b in reversed(g[:i]) if b['label'] == 'base' and ok(b)), None)
after = next((b for b in g[i + 1:] if b['label'] == 'base' and ok(b)), None)
refs = [b['median'] for b in (before, after) if b]
if not ok(r) or not refs:
out.append(dict(phase=ph, model=model, label=r['label'], seq=r['seq'], valid=False, rc=r.get('rc')))
continue
ref = sum(refs) / len(refs)
drift = abs(before['median'] - after['median']) / ref * 100 if before and after else 0.0
n = max(len(r.get('samples') or []), 1)
noise = 2 * 100 * (r.get('stdev') or 0.0) / math.sqrt(n) / ref
spread = max(drift, noise)
delta = (r['median'] - ref) / ref * 100
thr = max(MIN_PCT, spread)
out.append(dict(phase=ph, model=model, label=r['label'], seq=r['seq'], valid=True, ref=ref, tps=r['median'],
delta=delta, spread=spread, win=delta > thr, loss=delta < -thr))
out.sort(key=lambda d: d['seq'])
return out


def cmd_table(rows, phase=None):
for d in compare(rows, phase):
if not d['valid']:
print('%-8s %-4s %-44s FAILED/NO REFERENCE (rc=%s)' % (d['phase'], d['model'], d['label'], d.get('rc')))
else:
print('%-8s %-4s %-44s %8.2f vs %8.2f t/s %+6.2f%% spread %.2f%% %s' % (
d['phase'], d['model'], d['label'], d['tps'], d['ref'], d['delta'], d['spread'],
'WIN' if d['win'] else ('LOSS' if d['loss'] else '-')))


def cmd_screen(rows, min_pct, top):
seen = []
for d in sorted(compare(rows, 'screen'), key=lambda d: -d.get('delta', -1e9)):
if d['valid'] and d['delta'] >= min_pct and d['label'] not in seen:
seen.append(d['label'])
print('\n'.join(seen[:top]))


def cmd_winners(rows):
by = {} # label -> {model: d}
bad = set() # a failed / hung run on any model disqualifies the knob
for d in compare(rows, 'confirm'):
if d['valid']:
by.setdefault(d['label'], {})[d['model']] = d
else:
bad.add(d['label'])
best = {} # knob name -> (mean delta, label)
for label, ms in by.items():
if label in bad or not any(d['win'] for d in ms.values()) or any(d['loss'] for d in ms.values()):
continue
md = sum(d['delta'] for d in ms.values()) / len(ms)
name = label.split('=')[0]
if name not in best or md > best[name][0]:
best[name] = (md, label)
ranked = sorted(best.values(), reverse=True)
for md, label in ranked:
print('# winner %s mean delta %+.2f%% over %d model(s)' % (label, md, len(by[label])), file=sys.stderr)
print(' '.join(l for _, l in ranked[:5]))


def cmd_combo(rows):
cmd_table(rows, 'combo')
ds = [d for d in compare(rows, 'combo') if d['valid']]
if not ds:
print('VERDICT: no combo run'); return
wins = [d for d in ds if d['win']]; loss = [d for d in ds if d['loss']]
mean = sum(d['delta'] for d in ds) / len(ds)
print('VERDICT: combination mean %+.2f%% over %d model(s); %d win, %d loss -> %s' % (
mean, len(ds), len(wins), len(loss), 'candidate (still needs the greedy hash and the user)' if wins and not loss else 'do not use'))


if __name__ == '__main__':
a = sys.argv[1:]
if len(a) < 2:
raise SystemExit(__doc__)
rows = load(a[0]); c = a[1]
if c == 'table': cmd_table(rows, a[2] if len(a) > 2 else None)
elif c == 'screen': cmd_screen(rows, float(a[2]), int(a[3]) if len(a) > 3 else 99)
elif c == 'winners': cmd_winners(rows)
elif c == 'combo': cmd_combo(rows)
else: raise SystemExit('unknown cmd ' + c)
Loading
Loading