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
69 changes: 69 additions & 0 deletions tools/rdna3-w2/rocm-clr-fence-patch/Dockerfile.clr-patched
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# syntax=docker/dockerfile:1
#
# rdna3-clr-fence:local = rdna3-build:local + a CLR-patched libamdhip64.so.7 under
# /opt/rocm-clr-patched/lib, picked up through LD_LIBRARY_PATH (the llama.cpp binaries carry
# RUNPATH, so LD_LIBRARY_PATH wins over /opt/rocm/lib). With HIP_GRAPH_AGENT_FENCE unset the
# patched runtime behaves like stock. NOT a production image: never tag it llama-cpp-rocm:*.
#
# Build with build-clr.sh (CPU only, long; it applies the build lock and a job cap).
#
# Stock runtime this replaces: ROCm 10.1.0 (TheRock b324869fb3116353ac7eec5e6926aa3d452ac987,
# 10.1.0rc3), HIP 7.16.26385-0000000. Its CLR is projects/clr of
# https://github.com/ROCm/rocm-systems at 7da43026e4f2ef7600433c38c820732f7a205d22
# (pin_sha from /opt/rocm/core-10.1/share/therock/therock_manifest.json; rocm-systems has no
# tag for it, so it is fetched by SHA). TheRock applies no patches to rocm-systems at that pin.
#
# UNTESTED here: the CLR full build was not run in the prep wave (only a syntax check of the
# touched file). The apt list and cmake flags (copied from TheRock core/CMakeLists.txt hip-clr)
# are the first thing to adjust if the first build fails.

ARG ROCM_IMAGE=rocm/dev-ubuntu-24.04:10.1.0-full
ARG RUNTIME_BASE=rdna3-build:local

FROM ${ROCM_IMAGE} AS clr-build
ARG DEBIAN_FRONTEND=noninteractive
ARG ROCM_SYSTEMS_SHA=7da43026e4f2ef7600433c38c820732f7a205d22
ARG JOBS=6

RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake ninja-build git python3 python3-yaml pkg-config \
libgl-dev libegl-dev libnuma-dev libelf-dev libdrm-dev libx11-dev \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /src
RUN git init -q . \
&& git remote add origin https://github.com/ROCm/rocm-systems.git \
&& git sparse-checkout init --cone \
&& git sparse-checkout set projects/clr projects/hip \
&& git fetch --depth 1 --filter=blob:none origin "${ROCM_SYSTEMS_SHA}" \
&& git checkout -q FETCH_HEAD

COPY clr-agent-scope-fence.patch /tmp/clr-agent-scope-fence.patch
RUN git apply --check /tmp/clr-agent-scope-fence.patch && git apply /tmp/clr-agent-scope-fence.patch

# Flags follow TheRock core/CMakeLists.txt (hip-clr, non-Windows).
RUN cmake -S projects/clr -B /build -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_PREFIX_PATH=/opt/rocm \
-DHIP_PLATFORM=amd \
-DHIP_COMMON_DIR=/src/projects/hip \
-DCLR_BUILD_HIP=ON \
-DROCM_KPACK_ENABLED=ON \
-DUSE_NEW_HOSTCALL_IMPL=OFF \
-DHIPCC_BIN_DIR=

RUN nice -n 19 cmake --build /build --target amdhip64 -j"${JOBS}"

# Keep only the runtime library, named after its SONAME, and check the patch is inside.
RUN set -eux; \
lib="$(find /build -name 'libamdhip64.so*' -type f | head -n1)"; \
test -n "$lib"; \
mkdir -p /out/lib; cp "$lib" /out/lib/libamdhip64.so.7; \
ln -s libamdhip64.so.7 /out/lib/libamdhip64.so; \
readelf -d /out/lib/libamdhip64.so.7 | grep -q 'SONAME.*libamdhip64.so.7'; \
grep -qa HIP_GRAPH_AGENT_FENCE /out/lib/libamdhip64.so.7

FROM ${RUNTIME_BASE}
COPY --from=clr-build /out/lib /opt/rocm-clr-patched/lib
# Patched lib first; the stock directories stay behind it for every other dependency.
ENV LD_LIBRARY_PATH=/opt/rocm-clr-patched/lib:/opt/rocm/core-10.1/lib:/opt/rocm/lib
147 changes: 147 additions & 0 deletions tools/rdna3-w2/rocm-clr-fence-patch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# rocm-clr-fence-patch (prep only, nothing deployed, nothing built)

Question: is system-scope cache maintenance part of the ~2 us idle ROCm adds per dependent
kernel launch inside a HIP graph replay (TheRock#9241)? This directory holds an env-gated CLR
patch plus the Docker/build plumbing to test it. No GPU was used, no production image touched.

## Pinned runtime (read from the rdna3-build:local image, device-less)

- ROCm 10.1.0 (10.1.0rc3), TheRock b324869fb3116353ac7eec5e6926aa3d452ac987, HIP 7.16.26385-0000000
- base image `rocm/dev-ubuntu-24.04:10.1.0-full` (same as tools/Dockerfile and prodimg/Dockerfile)
- CLR = `projects/clr` of ROCm/rocm-systems at 7da43026e4f2ef7600433c38c820732f7a205d22
(TheRock manifest `pin_sha`, no TheRock patches on it). rocm-systems has no tag for this
pin, so everything fetches by SHA.

## Finding that changes the premise (read first)

The stock CLR at this pin already uses agent-scope fences for kernel dispatch packets:

- `AMD_OPT_FLUSH` defaults to 1 (rocclr/utils/flags.hpp) -> `Settings::fenceScopeAgent_`
(device.cpp) -> `dispatchPacketHeader_` is built with agent acquire+release for non-gfx12
(VirtualGPU ctor, rocvirtual.cpp). gfx1100 takes that path.
- Graph replay does not re-derive headers: packets are captured at instantiate time with that
header (dispatchAqlPacket capture branch) and replayed as flat batches by
`VirtualGPU::dispatchAqlPacketBatchFlat`. Only the first packet's acquire and the last packet's
release are raised to system, and only when `addSystemScope_` is pending.
- Barrier-AND packets inserted by the graph sync plan (`Device::CreateBarrierPacket`) already use
scope NONE.

So HIP_GRAPH_AGENT_FENCE=1 is expected to be close to a no-op: it only changes interior kernel
packets that were captured with system scope (a pending `addSystemScope_` at capture time, or
an event-bound launch) and it makes the boundary system scope unconditional. The binary was not
disassembled (no GPU, no runtime without a device); the flag name is present in the shipped
libamdhip64 and the source is the pinned commit, but the default value is NOT verified on the
binary. Expect to find, tonight, that mode 1 changes nothing.

Cheaper first test, no patch and no image (stock runtime, env var only):

GPURUN_OPTS='-e AMD_OPT_FLUSH=0' ./gpublock.sh ./lb.sh g-flush0 $B0 $G $GA -p 0 -n 128 -r 5
./gpublock.sh ./lb.sh g-flush1 $B0 $G $GA -p 0 -n 128 -r 5 # default

AMD_OPT_FLUSH=0 forces system scope on every dispatch. If tg is clearly slower (and tr.sh idle
clearly larger) with =0 than with the default, scope matters and the remaining gap to "no
fences" is worth the patch below. If =0 and default are within spread, fence scope is not the
~2 us and this whole task can be dropped. (rocm-runtime-knobs may already list AMD_OPT_FLUSH.)

## The patch (clr-agent-scope-fence.patch, 2 files, ~50 lines, applies to rocm-systems root)

- `rocclr/utils/flags.hpp`: new flag `HIP_GRAPH_AGENT_FENCE` (uint, default 0), read from the
environment like every CLR flag.
- `rocclr/device/rocm/rocvirtual.cpp`, `dispatchAqlPacketBatchFlat`: when the knob is non-zero
- interior kernel packets (index 1..n-2 of the batch handed to the call) get
mode 1: agent acquire + agent release; mode 2: NONE/NONE (see below);
- the first packet keeps/gets SYSTEM acquire and the last packet SYSTEM release, always
(addSystemScope_ is forced for the call);
- barrier-AND / barrier-value packets are not touched; the barrier bit is never touched.
- Knob unset = byte-identical stock behaviour (helper returns the input vector by reference).

Plan deviation: no change to hipamd/src/hip_graph*.cpp. In this CLR all graph replay goes
through that one function, and "boundary" batches are already split by the graph code at every
uncaptured node (D2H/H2D memcpy, host node, child graph), so the last packet of each call is
exactly "the node before a host-visible operation". An event record after the launch is a
separate marker command behind the last (system-release) packet.

Mode 2 (`HIP_GRAPH_AGENT_FENCE=2`) removes ALL interior fences (no L0/K$/I$ invalidate, no L2
writeback). It is UNSAFE: a dependent kernel can read stale L0/scalar-cache lines. It exists
only as a ceiling measurement ("how much idle is cache maintenance at all"); never trust its
output tokens, never run it for KLD. Use it only if mode 1 shows nothing and AMD_OPT_FLUSH=0
showed a difference; if mode 2 does not move idle either, the cost is CP packet processing or
wave launch ramp and the barrier bit is the next suspect.

Phase 2 (documented only, not implemented): drop the barrier bit (bit 8) on interior packets
of independent branches. Needs the dependency edges, which the flat batch does not carry;
the segmented-graph code in hip_graph_internal.cpp (`BuildSyncPlan`, per-segment batches) has
them. `hipExtAnyOrderLaunch` and `OptimizeStreamOrderingBarrier` are existing hooks.
llama.cpp graphs are mostly linear chains, so expect little.

## Correctness argument (mode 1)

- All interior packets run on one queue of one agent. AQL fences order work and cache state
between packets of one queue; agent scope makes the writes of packet k visible to every
wave on the same GPU (L2 is the agent coherence point on gfx1100) and invalidates the
non-coherent L0/scalar/instruction caches before packet k+1. Nothing outside the agent can
observe interior state, so system scope (which additionally writes back L2 to coherent host
mappings) buys nothing between kernels.
- Host/other-agent visibility is only required at the batch boundary, which keeps system
release (last packet) and system acquire (first packet).

## Failure modes to test for

1. Missing release before a host read: a kernel followed by hipMemcpyDtoH / host node / event
with host polling, where the kernel is not the last packet of its batch. Should not happen
(batches split at uncaptured nodes) but is the first thing that would show as stale host data.
2. Multi-queue graphs (DEBUG_HIP_FORCE_GRAPH_QUEUES, segmented graphs): cross-queue edges go
through HW-event barrier packets; producer's last packet has system release, consumer
queue's first packet system acquire, so still safe; test with llama.cpp graphs that split
(e.g. spec-decode verify graphs).
3. Zero-copy or pinned/host-visible buffers written by kernels in the middle of a batch and
read by the CPU while the graph is still running (e.g. a polling flag). Needs system release
at that kernel; the patch would break it. llama.cpp's single_sync / device-verify paths copy
results with explicit memcpy after the graph, so they should be fine; check anyway.
4. Cooperative/hostcall/printf-using kernels in the middle (not used by ggml-cuda).
5. Silent corruption (not crashes) is the failure shape: wrong tokens, NaNs, KLD != 0.

## Build (not done in this wave; CPU, long)

bash build-clr.sh --check # fetch pinned sources, git apply --check (done in prep: OK)
bash build-clr.sh # docker build -> rdna3-clr-fence:local (build lock, nice, -j6, needs >= 10 GB free)

The image is `rdna3-build:local` plus /opt/rocm-clr-patched/lib/libamdhip64.so.7 and
`ENV LD_LIBRARY_PATH=/opt/rocm-clr-patched/lib:/opt/rocm/core-10.1/lib:/opt/rocm/lib`.
Binaries built by the build image carry RUNPATH (checked on m104/bin/llama-bench), so
LD_LIBRARY_PATH wins. Check inside the image: `ldd $B0/llama-bench | grep amdhip`.
Do not tag it llama-cpp-rocm:*; build-clr.sh refuses.

Prep-wave checks done: `git apply --check` against a fresh sparse checkout of the pin;
syntax-only compile of rocvirtual.cpp (g++ -std=c++17 -fsyntax-only in the build image with
stub X11/GL/EGL headers, which the image lacks: rc=0, no new warnings); `docker build --check` on the Dockerfile;
`bash -n build-clr.sh`. The full CLR build was NOT run (cmake configure of CLR in the stock
image stops at `find_package(OpenGL)`; the Dockerfile installs libgl-dev for that. Other
missing packages are possible, see the note at the top of the Dockerfile).

## Test plan (tonight, only if the image exists; Qwen4/others are untouched by this)

Preamble P as in the wave plan ($B0, $G, $GA ...).

# baseline for the stock-env experiment first (no image needed), see above

# correctness, mode 1, full eval (must be 0 FAIL)
GPURUN_IMAGE=rdna3-clr-fence:local GPURUN_OPTS='-e HIP_GRAPH_AGENT_FENCE=1' \
./gpusmall.sh ./test2.sh w2-clr-all $B0 - '' '.'
# speed, with and without the env (interleaved, >= 3 reps; 5 for tg)
GPURUN_IMAGE=rdna3-clr-fence:local GPURUN_OPTS='-e HIP_GRAPH_AGENT_FENCE=1' \
./gpublock.sh ./lb.sh g-clr $B0 $G $GA -p 0 -n 128 -r 5
GPURUN_IMAGE=rdna3-clr-fence:local ./gpublock.sh ./lb.sh g-clr-off $B0 $G $GA -p 0 -n 128 -r 5
# KLD, must be exactly 0
./gpublock.sh ./kl.sh g-clr-base $B0 $G base $GA
GPURUN_IMAGE=rdna3-clr-fence:local ./gpublock.sh env KL_ENV=HIP_GRAPH_AGENT_FENCE=1 ./kl.sh g-clr $B0 $G test $GA
# idle: tr.sh with GPURUN_IMAGE set, env on vs off vs B0 (per-token idle ms)

Optional ceiling (output meaningless, timing only):
GPURUN_IMAGE=rdna3-clr-fence:local GPURUN_OPTS='-e HIP_GRAPH_AGENT_FENCE=2' ./gpublock.sh ./lb.sh g-clr2 $B0 $G $GA -p 0 -n 128 -r 5

Keep/abandon: abandon if per-token idle drops by less than 30% (baselines, idle ms of total
ms per token: Gemma 3.0/26.8, Nemotron 1.7/9.6, Qwen3.8 2.5/27) or the KLD / test2 gate fails.
The upper bound if scope is the whole story is about 1-2 ms/token on Gemma and 0.5 ms on
Nemotron; unproven. Also compare against the stock AMD_OPT_FLUSH=0/1 result above: if that
shows no scope sensitivity, abandon without building.
31 changes: 31 additions & 0 deletions tools/rdna3-w2/rocm-clr-fence-patch/build-clr.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash
# Build rdna3-clr-fence:local (patched libamdhip64.so.7 on top of rdna3-build:local).
# CPU only, long, needs network (GitHub). Never touches llama-cpp-rocm:* images or production.
# bash build-clr.sh build the image
# bash build-clr.sh --check only fetch the pinned CLR sources and git-apply --check the patch
set -euo pipefail
R=/home/tom/docker/projects/llama.cpp-RDNA3
HERE=$(dirname "$(readlink -f "$0")")
SHA=${ROCM_SYSTEMS_SHA:-7da43026e4f2ef7600433c38c820732f7a205d22}
TAG=${CLR_IMAGE_TAG:-rdna3-clr-fence:local}
JOBS=${JOBS:-6} # host: 15 GB RAM, Zen1 8C/16T; do not go above 6
case "$TAG" in llama-cpp-rocm:*) echo "refusing to tag $TAG" >&2; exit 2;; esac
[ "$JOBS" -le 6 ] || { echo "JOBS capped at 6" >&2; JOBS=6; }

if [ "${1:-}" = "--check" ]; then
T=$(mktemp -d "$HERE/chk.XXXXXX"); trap 'rm -rf "$T"' EXIT
cd "$T" && git init -q . && git remote add origin https://github.com/ROCm/rocm-systems.git
git sparse-checkout init --cone && git sparse-checkout set projects/clr projects/hip
git fetch -q --depth 1 --filter=blob:none origin "$SHA" && git checkout -q FETCH_HEAD
git apply --check "$HERE/clr-agent-scope-fence.patch" && echo "patch applies to rocm-systems@$SHA"
exit 0
fi

free_gb=$(df -BG --output=avail / | tail -1 | tr -dc 0-9)
[ "$free_gb" -ge 10 ] || { echo "only ${free_gb} GB free on /, need >= 10" >&2; exit 1; }
docker image inspect rdna3-build:local >/dev/null

flock "$R/build-bins/.build.lock" nice -n 19 \
docker build -f "$HERE/Dockerfile.clr-patched" -t "$TAG" \
--build-arg "ROCM_SYSTEMS_SHA=$SHA" --build-arg "JOBS=$JOBS" "$HERE"
echo "built $TAG; use it with GPURUN_IMAGE=$TAG (no GPU needed to build)"
Loading