From c3567d3f03cc5dce725514c182518ccf8d1e2275 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sat, 24 Oct 2026 23:47:26 +0000 Subject: [PATCH 01/27] deploy/compose, README: Ornith-1.5-122B containers Four containers on Hugging Face (keptn): FP8 and w4a8, each with MTP or DFlash2, on four cards. A compose file and a row in the models table for each; docs/DOCKER.md lists them and the two NVIDIA-Nemotron-3.5-Bolt-E4B files. --- README.md | 4 ++++ deploy/compose/ornith-1.5-122b-df2.yaml | 18 ++++++++++++++++++ deploy/compose/ornith-1.5-122b-w4a8-df2.yaml | 16 ++++++++++++++++ deploy/compose/ornith-1.5-122b-w4a8.yaml | 15 +++++++++++++++ deploy/compose/ornith-1.5-122b.yaml | 18 ++++++++++++++++++ docs/DOCKER.md | 10 ++++++++-- 6 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 deploy/compose/ornith-1.5-122b-df2.yaml create mode 100644 deploy/compose/ornith-1.5-122b-w4a8-df2.yaml create mode 100644 deploy/compose/ornith-1.5-122b-w4a8.yaml create mode 100644 deploy/compose/ornith-1.5-122b.yaml diff --git a/README.md b/README.md index 1a40b6a9..d02d3c7f 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,10 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | | Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` | +| Ornith-1.5-122B FP8, MTP, vision, four cards | `ornith-1.5-122b-fp8.rad` (118 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8) | `ornith-1.5-122b.yaml` | +| Ornith-1.5-122B FP8, DFlash2 drafter, vision, four cards | `ornith-1.5-122b-fp8-dflash2.rad` (116 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8-dflash2) | `ornith-1.5-122b-df2.yaml` | +| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), MTP, vision, four cards | `ornith-1.5-122b-w4a8.rad` (65 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8) | `ornith-1.5-122b-w4a8.yaml` | +| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), DFlash2 drafter, vision, four cards | `ornith-1.5-122b-w4a8-dflash2.rad` (64 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8-dflash2) | `ornith-1.5-122b-w4a8-df2.yaml` | | Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` | | Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | diff --git a/deploy/compose/ornith-1.5-122b-df2.yaml b/deploy/compose/ornith-1.5-122b-df2.yaml new file mode 100644 index 00000000..dfae8855 --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-df2.yaml @@ -0,0 +1,18 @@ +# Ornith-1.5-122B FP8 with incoai's DFlash2 drafter in place of the MTP head, on four cards with the +# host pool and the vision tower of ornith-1.5-122b.yaml. The drafter proposes 15 tokens in one pass, +# the depth radiance reads from the container. On four R9700s: 183 tok/s combined (BetterBench) +# against 165 with MTP, 342 against 194 on JSON, but 81 against 120 on prose; for chat, prose and +# many users take the MTP file. At 8 sequences the cache holds 690,992 tokens. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-df2 + command: > + --model /models/ornith-1.5-122b-fp8-dflash2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --placement expert_tiered --host-pool-mib 3072 --vision-tower-placement ram + --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml b/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml new file mode 100644 index 00000000..4f47d9d3 --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml @@ -0,0 +1,16 @@ +# Ornith-1.5-122B w4a8 (the weights of ornith-1.5-122b-w4a8.yaml) with incoai's DFlash2 drafter in +# place of the MTP head, every weight in VRAM on four cards. The drafter proposes 15 tokens in one +# pass, the depth radiance reads from the container. On four R9700s: 279 tok/s combined +# (BetterBench) against 217 with MTP, 556 against 256 on JSON, but 108 against 157 on prose; for +# chat, prose and many users take the MTP file. Sampling as ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-w4a8-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-w4a8-df2 + command: > + --model /models/ornith-1.5-122b-w4a8-dflash2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b-w4a8.yaml b/deploy/compose/ornith-1.5-122b-w4a8.yaml new file mode 100644 index 00000000..8bfcfa8a --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-w4a8.yaml @@ -0,0 +1,15 @@ +# Ornith-1.5-122B with four-bit experts (w4nl64, GPTQ), the trunk block-FP8, an int8 lm_head, its own +# MTP head and the vision tower: 65 GiB, every weight in VRAM on four cards, no host pool. At 8 +# sequences the cache holds 2,097,280 tokens, eight full 262,144-token sessions. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-w4a8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-w4a8 + command: > + --model /models/ornith-1.5-122b-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b.yaml b/deploy/compose/ornith-1.5-122b.yaml new file mode 100644 index 00000000..75c1ce3e --- /dev/null +++ b/deploy/compose/ornith-1.5-122b.yaml @@ -0,0 +1,18 @@ +# Ornith-1.5-122B, FP8 with one scale per 128x128 block, its own MTP head and the vision tower, on +# four cards. The 118 GiB of weights fill the cards: a pinned host pool of 3 GiB per card +# (--host-pool-mib counts per card) holds the experts that do not fit, and the vision tower sits in +# host memory. At 8 sequences the cache holds 614,208 tokens, two full 262,144-token sessions; a +# 16 GiB pool holds 2,097,280, but moves more experts over PCIe and decodes far slower. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b + command: > + --model /models/ornith-1.5-122b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --placement expert_tiered --host-pool-mib 3072 --vision-tower-placement ram + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/docs/DOCKER.md b/docs/DOCKER.md index bbfd6099..70141a50 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -133,6 +133,10 @@ the cards the engine runs on. | `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision | | `ornith-1.5-35b-a3b-w4a8.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | Ornith-1.5-35B-A3B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision | | `ornith-1.5-35b-a3b-w4a8-tp1.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | The same on one card, every weight in VRAM | +| `ornith-1.5-122b.yaml` | `ornith-1.5-122b-fp8.rad` | Ornith-1.5-122B, FP8, MTP, vision, on four cards with a 3 GiB pinned host pool per card and the vision tower in host memory | +| `ornith-1.5-122b-df2.yaml` | `ornith-1.5-122b-fp8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head | +| `ornith-1.5-122b-w4a8.yaml` | `ornith-1.5-122b-w4a8.rad` | Ornith-1.5-122B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision, every weight in VRAM on four cards | +| `ornith-1.5-122b-w4a8-df2.yaml` | `ornith-1.5-122b-w4a8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head | | `sage-a1.5.yaml` | `sage-a1.5-fp8.rad` | Sage-A1.5, FP8, MTP, vision | | `sage-a1.5-tp1.yaml` | `sage-a1.5-fp8.rad` | The same on one card: the expert plane partly in an 8 GiB pinned host pool, one 262,144-token session | | `sage-a1.5-df2.yaml` | `sage-a1.5-fp8-df2.rad` | Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, vision | @@ -143,6 +147,8 @@ the cards the engine runs on. | `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 | | `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower | | `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) | +| `nemotron-3.5-bolt-e4b-bf16.yaml` | `nemotron-3.5-bolt-e4b-bf16.rad` | NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B) in bf16 with NVIDIA's DFlash drafter, the vision tower in pinned host memory, on one card | +| `nemotron-3.5-bolt-e4b-i8g.yaml` | `nemotron-3.5-bolt-e4b-i8g.rad` | The same with the trunk at int8 (i8a8) | | `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) | | `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards | | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | @@ -178,7 +184,7 @@ docker compose -f flashnext.yaml down # stop ``` Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`, -`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml` and the files that read `RADIANCE_GPU` take one, `glm53-flash.yaml` -eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and +`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml`, the `nemotron-3.5-bolt-e4b-*.yaml` files and the files that read `RADIANCE_GPU` take one, the +`ornith-1.5-122b*.yaml` files four, `glm53-flash.yaml` eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and the dashboard page answer without the API key, and the health check fetches `/health` with busybox's `wget`. From 49a02c79df8d6852b9cee06386df53ef440f3d0b Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sun, 25 Oct 2026 01:55:35 +0000 Subject: [PATCH 02/27] deploy/compose, README: NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit container The feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8, on one card; the recipe is gemma4-e4b-bf16-a4-df.recipe with GPTQ for the int4 linears. Needs main from 248ecf5 (a4, #214). --- README.md | 1 + deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml | 17 +++++++++++++++++ docs/DOCKER.md | 1 + 3 files changed, 19 insertions(+) create mode 100644 deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml diff --git a/README.md b/README.md index d02d3c7f..3d641ddb 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-bf16.rad` (16 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-i8g.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` | +| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-a4.rad` (11 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | diff --git a/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml b/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml new file mode 100644 index 00000000..0b61c0ca --- /dev/null +++ b/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml @@ -0,0 +1,17 @@ +# NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B, post-trained by NVIDIA) at 4 bits on one card: the +# feed-forward as asymmetric int4 (GPTQ; w4a8i8_asym, w4a16_asym at decode heights), attention and +# layers 19-23 at i8a8, NVIDIA's DFlash drafter (7 tokens a pass) and the bf16 vision tower in pinned +# host memory. bf16 KV. Thinking is off, as in NVIDIA's template; switch it per request +# (chat_template_kwargs). Sampling as NVIDIA states it (temperature 1.0, top_p 0.95) and the +# checkpoint's top_k 64. +name: radiance-nemotron-3.5-bolt-e4b-a4 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-nemotron-3.5-bolt-e4b-a4 + command: > + --model /models/nemotron-3.5-bolt-e4b-a4.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype bf16 + --num-speculative-tokens 7 --mm-max-patches 2520 --vision-tower-placement ram + --temp 1.0 --top-p 0.95 --top-k 64 --chat-template-kwargs '{"enable_thinking":false}' diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 70141a50..a2e12dd3 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -149,6 +149,7 @@ the cards the engine runs on. | `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) | | `nemotron-3.5-bolt-e4b-bf16.yaml` | `nemotron-3.5-bolt-e4b-bf16.rad` | NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B) in bf16 with NVIDIA's DFlash drafter, the vision tower in pinned host memory, on one card | | `nemotron-3.5-bolt-e4b-i8g.yaml` | `nemotron-3.5-bolt-e4b-i8g.rad` | The same with the trunk at int8 (i8a8) | +| `nemotron-3.5-bolt-e4b-a4.yaml` | `nemotron-3.5-bolt-e4b-a4.rad` | The same with the feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8 | | `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) | | `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards | | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | From 6d6541af424492fa38fbb354f732bc2f1f0db598 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sat, 24 Oct 2026 15:02:28 +0000 Subject: [PATCH 03/27] docker: libopenblas-dev in the build stage, so libquant's GPTQ uses LAPACK --- Dockerfile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Dockerfile b/Dockerfile index d0c0c375..8963f833 100644 --- a/Dockerfile +++ b/Dockerfile @@ -140,9 +140,12 @@ ARG JOBS= # libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which # mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's # AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image. +# libopenblas-dev: libquant's GPTQ factorises its Hessians through LAPACK where it finds OpenBLAS +# (libquant/CMakeLists.txt); without it rad-convert's gptq rule runs single-threaded loops. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \ + libopenblas-dev \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg From 32881da9fddc8e18273653ad1674ca3744e2449f Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 25 Oct 2026 07:34:29 +0000 Subject: [PATCH 04/27] docs/GUIDE: two engines on one R9700 pair -- the driver's queue split (amdgpu.num_kcq) and the start order The four compute queue slots the GUIDE names are what amdgpu leaves to user queues while it keeps four of the card's eight for its own kernel queues. With num_kcq=0 MES maps all eight (compute_hqd_mask 0xf), two engines' queues fit, and the weight reads beside the all-reduces can stay on. The order the engines create their second-lane queues decides where MES places them, so the first engine should serve one request before the second starts. Measured with Qwen3.8-27B and TranslateGemma 27B on two R9700s. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/GUIDE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 1bb8efed..b536efbc 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3475,6 +3475,8 @@ minutes of concurrent long prompts on both without a stall. The ceiling costs pr reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapped, 9.8 s at 64, 10.3 s at 32. Give the engine started first its `--gpu-headroom-mib` for the second. A model whose decode reads weights ahead on a second queue (Gemma 4 without chained launches) slows sharply beside a second server: an R9700 has four compute queue slots and the two servers hold eight, so every decode step waits for a queue switch. Gemma 4 31B at TP4 beside an idle Qwen3.8-Flash-Next went from 13 ms to 41 ms a step; with `RADIANCE_PREFETCH_BESIDE=0` in the Gemma engine it took 13.8 ms. +The four slots are what the amdgpu kernel driver leaves to user queues. It keeps compute queues of its own for submissions through the graphics stack (Vulkan and OpenGL in Mesa), four of the eight on the card's two compute pipes by default (`num_cp_queues 4` in `/sys/class/kfd/kfd/topology/nodes/*/properties`). A machine that drives its cards through ROCm alone can give them back with the module option `amdgpu.num_kcq=0` (a line `options amdgpu num_kcq=0` in `/etc/modprobe.d/`, then `update-initramfs -u` and a reboot): `num_cp_queues` reads 8 and `dmesg` shows `compute_hqd_mask 0x0000000f` (`num_kcq=1` leaves `0x0000000e`, three queues a pipe, though `num_cp_queues` reads 7). An engine holds up to four queues a card (the step's lane, the second lane, the mover's and the runtime's own), so two engines then fit and the weight reads can stay on. Start them one after the other and send the first a short request before starting the second: an engine creates its second-lane queue at the first step that uses it (a decode step where the weight reads or another second-lane op run), and a queue created after the other engine's queues lands where both run slower (TranslateGemma one stream 120 t/s instead of 181, Qwen beside a busy TranslateGemma 50 ms a step instead of 43). Qwen3.8-27B and TranslateGemma 27B on two R9700s, the reads on in both: TranslateGemma one stream 180.6-180.9 t/s and Qwen beside a busy TranslateGemma 42.9 ms a step, against 152-154 t/s and 41.0-42.8 ms with the default slots and `RADIANCE_PREFETCH_BESIDE=0` in both; Qwen beside an idle TranslateGemma 18.3 ms a step, against 19.8-20.5. Mesa then finds no compute ring of its own on those cards. + **Tooling** | | | From 486c93316111f0e16978d3ee32683ae0d3b37dd0 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Sat, 24 Oct 2026 19:19:19 +0700 Subject: [PATCH 05/27] device and plugin boundary: kv_resolve, the streamed store rows, ABI 30 --- abi/rad_abi.h | 46 +- abi/rad_runtime.h | 67 +++ core/device/aql.cpp | 49 +- core/device/device.h | 22 +- core/device/dispatch.cpp | 9 +- core/device/host.cpp | 1 + core/runtime/ctx.cpp | 20 +- core/runtime/ctx.h | 58 ++- core/runtime/issue.cpp | 15 +- core/runtime/kvbind.cpp | 10 +- core/runtime/tierexec.cpp | 15 +- core/runtime/xprefetch.cpp | 2 +- docs/KERNELS.md | 6 + docs/OPS.md | 192 +++++++- libavx/CMakeLists.txt | 1 + libavx/avx_attn.cpp | 96 ++++ libavx/avx_cases.cpp | 41 ++ libavx/avx_check_hand.cpp | 477 ++++++++++++++++++ libavx/avx_isa.h | 2 +- libavx/avx_kvstream.cpp | 403 +++++++++++++++ libavx/avx_registry.cpp | 42 ++ libr4d/CMakeLists.txt | 1 + libr4d/r4d_fuse.cpp | 37 ++ libr4d/r4d_kv_resolve.hip | 814 +++++++++++++++++++++++++++++++ libr4d/r4d_model_bf16.hip | 152 ++++++ libr4d/r4d_plugin.h | 10 + libr4d/r4d_qk_norm_rope_gate.hip | 135 ++++- libr4d/r4d_rows.cpp | 188 +++++++ libr4d/r4d_shapes.cpp | 84 ++++ libref/ref_attn.cpp | 120 +++++ libref/ref_kvstream.cpp | 453 +++++++++++++++++ libref/ref_ops.h | 6 + libref/ref_registry.cpp | 42 ++ libref/ref_shapes.cpp | 56 +++ 34 files changed, 3643 insertions(+), 29 deletions(-) create mode 100644 libavx/avx_kvstream.cpp create mode 100644 libr4d/r4d_kv_resolve.hip create mode 100644 libref/ref_kvstream.cpp diff --git a/abi/rad_abi.h b/abi/rad_abi.h index fe7d8223..7399a732 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -14,11 +14,47 @@ extern "C" { /* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h, * rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or - * rad_spechub.h. Every - * kind of plugin reports it, and a plugin that does not report exactly this version is refused at - * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a - * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 27u + * rad_spechub.h. Every kind of plugin reports it, and a plugin that does not report exactly this + * version is refused at load with both versions printed. A new optional export (e.g. + * rad_plugin_reference) is not a + * change of shape: a plugin without it gets the default. + * + * 26: RadKVGroupBatch grows one trailing, zero-defaulted field (`stream`, a RadKVStream) so a + * plugin can see a streamed KV group's ring, residency map and host mirror, and RadBuildCtx grows + * `kv_resident_blocks` and `kv_stream_ok` (--kv-resident and the architecture's capability). Every + * earlier field keeps its offset, but the structs are larger, so out-of-tree plugins must be + * rebuilt against 26. + * + * 27: RadBuildCtx grows `cvec`, a rank's control-vector direction table (control vectors). Trailing + * and zero-defaulted as above, so a plugin built against 26 keeps every offset. + * + * 28: RadArchProbe grows two trailing, zero-defaulted fields that met in the same merge: + * `chain_pays` (the plugin measured its speculative step faster with chained launches) and + * `kv_stream_ok` (the architecture can move a KV group between host memory and a resident ring). + * Both are additions a 27 plugin never reads; a plugin that does set them must be built against + * 28, since 27's struct ends where these begin. + * + * 29: radiance 1.11.0's Unlimited-OCR and control-vector work meets KV streaming. RadBuildCtx + * grows `attn_prefill_fp8` (--attn-prefill-fp8, the prefill attention's products accepted in + * e4m3); it fills the four padding bytes ABI 28 already had after `kv_quant`, so no field moves. + * RadArchProbe grows `control_vector_ok` after ABI 28's `kv_stream_ok`: upstream 1.11.0 had it at + * the offset `kv_stream_ok` took in 28, so it moves to 80 and the struct grows, which is why this + * is a bump. Both trailing fields are zero-defaulted, but a plugin that sets either must be built + * against 29. + * + * 30: radiance 1.12.0 meets KV streaming. Upstream spent 27 on its own additions and this tree had + * already spent it, so the merge takes the next number for both: upstream's `RadBuildCtx` grows + * `tp_attn_rows`, `state_dtype` (--state-cache-dtype f16) and `draft_coupling`, and gains + * `rad_lane1_window_begin/end` and `rad_drafter_short_block`; `RadArchProbe` grows + * `tp_attn_rows_ok` and `state_f16_ok`; `RadAudioGenBatch` grows `prev_slot`/`prev_pos`/ + * `prev_used` and the reference prompt's `n_ref`/`ref_samples`/`ref_audio`/`ref_cu`/`ref_cu_h`/ + * `ref_frame`/`ref_frame_h`; `RadAudioGenDecl` grows `branches`, `input_special` and the + * `tmpl_ref`/`ref_*` reference template; and the plugin ABI gains `rad_spechub.h` (a whole new + * header) with the per-row `rad_kernel_reference` override. Every upstream field is trailing and + * zero-defaulted, and `RadKVStream` loses our never-read `scratch` (80 -> 72 bytes), so a plugin + * built against 26-29 keeps the offsets it reads only if it is rebuilt; the loss of a middle + * pointer in `RadKVStream` is why this is a bump even before upstream's additions. */ +#define RAD_ABI_VERSION 30u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index aa684371..07488d31 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -22,6 +22,56 @@ typedef struct RadCtx RadCtx; * scheduler and the run phase the bounds without a device read. */ enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 }; +/* ================================================================== KV streaming */ +/* A streamed KV group keeps its whole context in pinned host memory and only a ring of blocks on + * the card (docs/KV-STREAMING.md §3.2, §3.6, §4.2). The step batch carries this view of that + * group; a group whose KV is fully resident has none. + * + * Why one pointer to a struct rather than fields inside RadKVGroupBatch: the data is per group + * and fixed at bring-up, while the batch is rebuilt per step for every rank, so copying its + * pointers and geometry per group into every step's batch would be work that never changes. One + * trailing pointer also keeps a group's own layout as it was for every plugin that does not + * stream: the field is zero-defaulted, and a null `stream` means the group is fully resident and + * has no ring, no map and no host copy. + * + * The layout mirrors the pool, layer by layer: a layer's mirror is a dense run of `blocks` rows + * of `block_bytes`, and `host_layer_stride` is `blocks * block_bytes`. So layer l's row for block + * b is at `host + l * host_layer_stride + b * block_bytes`, and `block_bytes` is both the row + * pitch `kv_resolve` reads the mirror at and the length of every copy into the ring. + * + * `res`, `slot_block`, `slot_state` and `ctl` are device memory: a resolve launch reads and + * rewrites them every step, so a host round trip per lookup would cost the link latency the ring + * exists to avoid. Nothing here changes address for the engine's life, which is what lets a + * recorded pass replay a resolve. */ +typedef struct RadKVStream { + /* The group's mirror, pinned host memory, RAD_MEM_HOST_MAPPED so a device kernel reads it over + * the link in place. `blocks * bytes_per_block` bytes, all layers, zeroed at bring-up: a block + * no store has written yet reads as zeros rather than as whatever the page held. */ + uint8_t* host; + /* Residency, both directions, ONE SLICE A LAYER: `res` is block -> ring slot or -1 (device, + * `n_layers * blocks` entries, layer l at `res + l * blocks`), `slot_block` is slot -> block or + * -1 (`n_layers * slots`), `slot_state` is `n_layers * slots * 2`: the epoch of a slot's last + * use and its CLOCK reference bit. A block is resident per layer because the resolve copies one + * layer's bytes; a group-wide map would call a block resident for a layer that was never + * copied. `ctl` is shared: its counters and overflow latch are the group's. */ + int32_t* res; + int32_t* slot_block; + int32_t* slot_state; + /* The control block: epoch, clock hand, the last launch's miss count, the overflow latch, and + * the cumulative misses/lookups/calls counters (docs/OPS.md "kv_resolve"). */ + int32_t* ctl; + /* Bytes one block of ONE layer occupies: the mirror's row pitch and the ring's slot pitch. */ + int64_t block_bytes; + /* Bytes one layer of the mirror occupies, i.e. the distance between layer l and layer l+1. */ + int64_t host_layer_stride; + /* Ring depth in blocks: the group's device pool is `slots` blocks deep while a selection names + * block ids over the group's whole context. */ + int64_t slots; + /* Bytes the host mirror occupies, all layers (`blocks * block_bytes * n_layers`), so a caller + * that only has this view can report or check the off-card tier. */ + int64_t host_bytes; +} RadKVStream; + typedef struct RadKVGroupBatch { rad_kvgroup group; int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */ @@ -36,6 +86,10 @@ typedef struct RadKVGroupBatch { int64_t state_index_pitch; int64_t block_size; int64_t max_blocks; + /* Null unless this group's KV streams: the mirror, the residency map and the ring's geometry + * (RadKVStream above). Trailing and zero-defaulted, so a plugin built against ABI 25 reads + * every field it knows at the same offset and simply never sees the ring. */ + const RadKVStream* stream; } RadKVGroupBatch; typedef struct RadBatch { @@ -721,6 +775,19 @@ int rad_step_fail(RadCtx* c, const char* what); /* ================================================================== run-phase queries */ const RadBatch* rad_batch(RadCtx* c); +/* The position of absolute model layer `layer` in the cache `group` holds, or -1 when this rank + * has no pool for it or the group does not hold that layer. It is the same lookup a RAD_KV operand + * makes (KVPoolBinding::layer_slot), and the index a streamed group's host mirror is laid out by: + * layer `i` of the group is at `stream->host + i * stream->host_layer_stride`. A group's bound + * layers need not be contiguous, so this is never `layer` itself. */ +int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer); +/* Prefill staging (docs/KV-STREAMING.md §4.1). When the group's pass selected the one-layer stage + * view, copy this layer's whole host-mirror row into it, on the compute stream, after the layer's + * store and before its attention; returns 1 and the caller must not resolve. Returns 0 when the + * group has no stage view (a resident group, or the parity configuration's context-sized ring) and + * the caller proceeds normally. The ordering rule is in core/kvstream/stage.h. */ +int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, + int layer); int rad_rank(RadCtx* c); int rad_world_size(RadCtx* c); RadStream rad_stream(RadCtx* c); diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 748d74bd..046d1de5 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -2668,9 +2668,10 @@ int64_t a_gate_room(RadStream rs) { /* Waits for the mark, then for the card's link gate if a collective has ever held it (under TP * the all-reduce shares the link and the step waits on it, not on these copies), copies, writes - * `done`, then the list's number. */ + * `done`, then the list's number. RAD_XP_NO_YIELD skips the gate: a list the compute stream waits on + * cannot outlast a hold whose release is behind that wait (core/kvstream/stage.cpp). */ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, - uint32_t* done, uint32_t done_val) { + uint32_t* done, uint32_t done_val, unsigned flags) { DmaQueue* dq = xp_queue(ord); if (!dq) return RAD_E_UNSUPPORTED; Sig* in = (Sig*)mark; @@ -2684,7 +2685,8 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; rc = dma_put(dq, poll, 6); } - if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle) { + if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle && + !(flags & RAD_XP_NO_YIELD)) { const uint64_t ga = (uint64_t)lane->gate.handle + offsetof(amd_signal_t, value); const uint32_t gate[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, (uint32_t)ga, (uint32_t)(ga >> 32), 0u, 1u /* the low bit */, @@ -2719,6 +2721,34 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d return rc; } +/* An event the DMA engine completes (rad_event_dma): a fresh completion word for the event, which + * a rad_xp_list writes 0 to as its `done` once its bytes have landed, so a stream that waits on the + * event stops until the copy is done. + * + * The word comes back at 0 and the *caller* arms it with a write of 1 on the stream, because the arm + * must be ordered: a host store here would land ahead of a wait still queued for the group's previous + * copy (which would then block on this 1 and never see its 0), and an event record would not do + * either -- a record completes by decrementing its signal to 0, which is the value the wait is + * looking for. A fresh signal each time keeps two uses of one word from overlapping at all. */ +int a_event_dma(RadEvent re, RadStream rs, uint32_t** word) { + if (!word) { device_set_error("rad_event_dma: null word"); return RAD_E_INVAL; } + if (capturing()) { + device_set_error("rad_event_dma: a tape cannot record a DMA list; the caller must re-run " + "this call with the tape paused"); + return RAD_E_STATE; + } + Event* e = ev_of(re); + Stream* s = ours(rs); + if (!e || !s) { device_set_error("rad_event_dma: null or foreign argument"); return RAD_E_INVAL; } + Sig* g = sig_get(e->host); + if (!g) { device_set_error("rad_event_dma: no signal could be made"); return RAD_E_DEVICE; } + hsa_signal_silent_store_relaxed(g->h, 0); + g->agent = s->agent; + record_adopt(e, g); + *word = (uint32_t*)(uintptr_t)sig_value_addr(g); + return RAD_OK; +} + int64_t a_xp_behind(int ord) { DmaQueue* dq = (ord >= 0 && ord < kMaxDevices) ? &g_dma_xp[ord] : nullptr; if (!dq || !dq->tried.load(std::memory_order_acquire) || !dq->ok) return 0; @@ -3376,9 +3406,17 @@ void* pin_pieces(int64_t bytes) { char* const p = (char*)at; prefer_numa_node(p, len, current_card_numa_node()); + /* RADIANCE_NO_HUGE_PAGES asks for small pages, before the pin faults them in: the KV mirror's + * scattered 2 KiB reads are the case page size is supposed to matter for, and this is how that + * is measured rather than assumed (core/kvstream/mirror.cpp). Not a supported mode. */ + const bool small_pages = std::getenv("RADIANCE_NO_HUGE_PAGES") != nullptr; if (len >= ((int64_t)2 << 20)) { - ::madvise(p, (size_t)len, MADV_HUGEPAGE); - warn_if_no_huge_pages(); + if (small_pages) { + ::madvise(p, (size_t)len, MADV_NOHUGEPAGE); + } else { + ::madvise(p, (size_t)len, MADV_HUGEPAGE); + warn_if_no_huge_pages(); + } } (void)::madvise(p, (size_t)len, MADV_DONTFORK); @@ -3604,6 +3642,7 @@ const DeviceBackend* aql_backend_if_present(void) { g_aql.stream_gate = a_stream_gate; g_aql.gate_open = a_gate_open; g_aql.gate_room = a_gate_room; + g_aql.event_dma = a_event_dma; return &g_aql; }(); return b; diff --git a/core/device/device.h b/core/device/device.h index 0d9655ce..16f99d1e 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -113,13 +113,27 @@ extern "C" void* rad_link_gate(RadStream s); * counts lists handed over and not yet finished. The prefetch ring is uncached device memory * (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a * slot's previous contents. */ +/* An event the DMA engine completes instead of a dispatch: it is recorded on `s` (a write of 1 to + * its completion word, in stream order) and `*word` returns that word for `rad_xp_list` to write 0 + * to as the list's `done`, once the list's bytes have landed. `rad_event_wait(s, ev)` then stops `s` + * until the copy is done, device-side: no host round trip on the step path. The caller waits for + * the group's previous copy before arming the next, so the word's older 0 cannot release a later + * wait. RAD_E_STATE while a tape is recording: a list is not a queue packet, so a recorded pass + * must re-run the call with the tape paused (core/kvstream/stage.cpp). */ +extern "C" int rad_event_dma(RadEvent ev, RadStream s, uint32_t** word); extern "C" int rad_xp_supported(int device); extern "C" int rad_xp_stream_create(RadStream* out); extern "C" int rad_ride(RadStream s, void** token); extern "C" int rad_ride_wait(RadStream s, void* token); extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets); +/* `flags` RAD_XP_NO_YIELD: the list does not give way to a link a stream of this card holds. A copy + * the compute stream itself waits on must set it -- a yield it cannot outlast is a deadlock (the + * hold's release is behind the wait) -- at the cost of taking its share of the link in one piece + * (core/kvstream/stage.cpp). The expert prefetch passes 0: nothing waits for it. */ +#define RAD_XP_NO_YIELD 1u extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, - const uint64_t* bytes, uint32_t* done, uint32_t done_val); + const uint64_t* bytes, uint32_t* done, uint32_t done_val, + unsigned flags); extern "C" int64_t rad_xp_behind(int device); extern "C" void* rad_dev_alloc_uncached(int64_t bytes); extern "C" void rad_dev_free_uncached(void* p); @@ -316,7 +330,7 @@ struct DeviceBackend { int (*ride_wait)(RadStream s, void* token); void (*ride_release)(void* token, RadStream after, int64_t packets); int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, - const uint64_t* bytes, uint32_t* done, uint32_t done_val); + const uint64_t* bytes, uint32_t* done, uint32_t done_val, unsigned flags); int64_t (*xp_behind)(int device); void* (*alloc_uncached)(int64_t bytes); void (*free_uncached)(void* p); @@ -325,6 +339,10 @@ struct DeviceBackend { int (*stream_gate)(RadStream s, void** gate); int (*gate_open)(void* gate); int64_t (*gate_room)(RadStream s); + + /* ---- an event a DMA list completes: see rad_event_dma. Null (unsupported) on a backend with + * no DMA queue that writes a completion word. */ + int (*event_dma)(RadEvent e, RadStream s, uint32_t** word); }; diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index cf075dd6..16b20d6f 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -549,6 +549,11 @@ void rad_event_destroy(RadEvent e) { dev()->event_destroy(e); } int rad_event_record(RadEvent e, RadStream s) { return dev()->event_record(e, s); } +int rad_event_dma(RadEvent e, RadStream s, uint32_t** w) { + if (const auto f = dev()->event_dma) return f(e, s, w); + rad::device_set_error("rad_event_dma: the device backend has no DMA queue to complete an event"); + return RAD_E_UNSUPPORTED; +} int rad_event_wait(RadStream s, RadEvent e) { return dev()->event_wait(s, e); } int rad_event_query(RadEvent e) { return dev()->event_query(e); } int rad_event_sync(RadEvent e) { @@ -630,8 +635,8 @@ void rad_ride_release(void* token, RadStream after, int64_t packets) { if (const auto f = dev()->ride_release) f(token, after, packets); } int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, - uint32_t* done, uint32_t done_val) { - if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val); + uint32_t* done, uint32_t done_val, unsigned flags) { + if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val, flags); return RAD_E_UNSUPPORTED; } int64_t rad_xp_behind(int device) { diff --git a/core/device/host.cpp b/core/device/host.cpp index d404a2bb..d66be6e4 100644 --- a/core/device/host.cpp +++ b/core/device/host.cpp @@ -816,6 +816,7 @@ const DeviceBackend g_host = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, h_stream_gate, h_gate_open, h_gate_room, + nullptr, /* no DMA queue, so no event it could complete */ }; } /* namespace */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index ca8e322b..2db02d28 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -3,6 +3,8 @@ */ #include #include "ctx.h" +#include "kvstream/bind.h" +#include "kvstream/stage.h" #include "xp_state.h" #include "../device/device.h" @@ -921,7 +923,7 @@ int Ctx::lane_join(int from, int to) { * (below). */ static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); -static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72, +static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); uint64_t Ctx::pass_key(const RadBatch* b) const { @@ -957,6 +959,11 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table); mix((uint64_t)k.block_table_pitch); ptr(k.seqused); ptr(k.state_index); mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks); + /* Null on a fully resident group, a fixed set of addresses on a streamed one. Two groups + * that differ here hand a kernel different memory, so they are different passes -- and the + * view's *address* must not enter the key: the builder's Out slot rotates every step, which + * would make every streamed pass a new one (kvstream/bind.h, kvstream_view_key). */ + mix(kvstream_view_key(k.stream)); } mix((uint64_t)level_); mix(dense_epoch_); @@ -1229,6 +1236,12 @@ int Ctx::play_pass(PassTape& t) { rc = xp_ ? xp_step_run(st.a) : RAD_OK; lane_ = l0; break; + case kTapeKvStage: + case kTapeKvStageAfter: + lane_ = st.lane; + rc = kvstage_run(this, st.a, st.b, st.kind == kTapeKvStageAfter); + lane_ = l0; + break; } if (rc < 0) { if (step_status_ >= 0) step_status_ = rc; @@ -1254,7 +1267,8 @@ int Ctx::run_pass(const RadBatch* b) { /* A pass the stager armed for is issued live: see runtime/stager.h. */ if (!tape_on_ || staging_) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } const uint64_t key = pass_key(b); - if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } + if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); + return RAD_OK; } if (std::find(tape_refused_.begin(), tape_refused_.end(), key) != tape_refused_.end()) { bump(pc_refused_); arch_step_(this, b); @@ -1320,7 +1334,6 @@ int Ctx::run_pass(const RadBatch* b) { } int Ctx::run_step(const RadBatch* b) { - if (!b) return RAD_E_INVAL; if (!arch_step_) { RAD_WARN("Ctx::run_step: no architecture step function was installed"); @@ -1337,6 +1350,7 @@ int Ctx::run_step(const RadBatch* b) { step_status_ = RAD_OK; step_fail_.clear(); prof_n_ = 0; + kvstream_enter(this, b); { const int rc = run_pass(b); if (rc < 0 && step_status_ >= 0) step_status_ = rc; diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 303cfaa3..3a52cddf 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -141,6 +141,18 @@ struct RouteSlot { * LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]] * CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time */ +/* One of the two views a streamed group's allocation is addressed through. `depth` is the number + * of layer stripes the view presents: the ring keeps the group's `n_layers`, the stage presents + * one and every layer aliases offset 0. The field is a depth and NOT a rewritten `layer_slot`: + * that table is also the host mirror's row (rad_kv_layer_index), so collapsing it would write all + * layers into one mirror row (docs/KV-STREAMING.md §3.5.1). */ +struct KVViewState { + int64_t layer_stride = 0; + int64_t bytes = 0; + int64_t depth = 0; /* 0: n_layers; 1: every layer at offset 0 */ + int64_t shape0 = 0; /* the operand's [blocks] extent for this view */ +}; + struct KVPoolBinding { void* base = nullptr; int64_t layer_stride = 0; /* bytes between one layer's cache and the next */ @@ -152,8 +164,26 @@ struct KVPoolBinding { std::vector layer_slot; uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */ int64_t shape[RAD_MAX_RANK] = {0}; + /* The active view's stripe count: 0 is n_layers, 1 is the one-layer prefill stage. */ + int64_t depth = 0; + /* Both fixed views over the group's one allocation. The ring is always present; the stage only + * for a group whose plan depth is 1 (its ring is smaller than its context). The active fields + * above are set from one of these before each pass (kvstream_enter), so a recorded pass that + * used a view replays against it: the pass key already carries the phase, which selects it. */ + KVViewState ring; + KVViewState stage; + bool has_stage = false; + /* Bytes of one layer's mirror row a staged pass must copy, from the block manager's highest + * held block (kvstream/stage.h). 0 copies the whole row, which is always correct and is what a + * caller with no manager (a test, a harness) leaves it at. Set once per step, before the pass, + * because the bound grows as a prefill appends blocks. */ + int64_t stage_live_bytes = 0; }; +/* The KV stage's driver, run again where a recorded pass made it (kvstream/stage.cpp). `after` is + * the call the architecture makes after a layer's attention instead of before it. */ +int kvstage_run(Ctx* c, int group, int layer, bool after); + struct CtxDesc { Program* program = nullptr; int rank = 0; @@ -213,6 +243,20 @@ public: int rank() const { return rank_; } /* Whether repeated passes are recorded and played back (prepare() says when they are not). */ bool records_passes() const { return tape_on_; } + /* Whether the pass being issued is being recorded. Work a tape cannot record -- a DMA + * submission -- must be re-run where the pass made it instead (tape_kv_stage). */ + bool recording() const { return rec_ != nullptr; } + /* While recording: a KV stage call becomes a host step that re-runs at every play, because the + * DMA list it hands the engine and the stream wait on the list's completion word are neither of + * them queue packets (kvstream/stage.cpp; xprefetch.cpp does the same for the prefetch). */ + int tape_kv_stage(bool after, int group, int layer) { + TapeStep st; + st.kind = (uint8_t)(after ? kTapeKvStageAfter : kTapeKvStage); + st.a = group; + st.b = layer; + return tape_host(st, [&] { return kvstage_run(this, group, layer, after); }); + } /* This rank's device ordinal, for the calls that name a card rather than a stream. */ + int device() const { return device_; } int world_size() const { return world_size_; } RadStream stream() const { return stream_; } Program* program() const { return program_; } @@ -230,6 +274,17 @@ public: void* weight_ptr(rad_weight w); void* buf_ptr(rad_buf b); + /* The group-local position of absolute model layer `layer` in the binding's layer_slot, or -1. + * rad_kv_layer_index (rad_runtime.h) exposes it to a plugin, which needs it for the host + * mirror: that is laid out by the group's layers, not by model layer numbers. */ + int64_t kv_layer_index(rad_kvgroup g, int layer) const; + /* The group's pool binding, for the view switch and the stage copy. */ + const KVPoolBinding* kv_binding(rad_kvgroup g) const { + return g < kv_.size() ? &kv_[(size_t)g] : nullptr; + } + KVPoolBinding* kv_binding(rad_kvgroup g) { + return g < kv_.size() ? &kv_[(size_t)g] : nullptr; + } /* ---------------------------------------------------------- routing (spec §5.5) */ int route_report(int layer, const RadRouting* r); @@ -435,7 +490,8 @@ private: * issue. A difference means the key misses a dependency; the step fails, naming the first * differing dispatch. */ enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3, - kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 }; + kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6, + kTapeKvStage = 7, kTapeKvStageAfter = 8 }; /* A prefetch call (Ctx::xp_predict), run again where the pass made it. */ struct TapeXp { RadPrefetchNext next{}; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index a8e7f245..5baf187c 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -19,6 +19,7 @@ #include #include "ctx.h" #include "device/device.h" +#include "kvstream/bind.h" #include "wtab.h" #include @@ -802,7 +803,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size()) ? b.layer_slot[(size_t)o.offset] : -1; - const int64_t off = layer * b.layer_stride; + const int64_t off = kv_binding_offset(b, layer); if (layer < 0 || (b.bytes && off + b.layer_stride > b.bytes)) return abort_step_msg(h, RAD_E_INVAL, fmt("operand %d asks KV group %u for layer %lld, which is " @@ -1044,6 +1045,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { g_iss_lau_p = g_iss_lau; } } else { + /* The launch alone, split from the band scan and operand resolution `own` covers above. */ s = ip.launch(la, cur_stream()); } if (hold) { @@ -1251,6 +1253,17 @@ int rad_step_fail(RadCtx* c, const char* what) { } const RadBatch* rad_batch(RadCtx* c) { return c ? static_cast(c)->batch() : nullptr; } + +int64_t rad::Ctx::kv_layer_index(rad_kvgroup g, int layer) const { + if (g >= kv_.size() || !kv_[g].base || layer < 0) return -1; + const std::vector& ls = kv_[g].layer_slot; + if ((size_t)layer >= ls.size()) return -1; + return ls[(size_t)layer]; +} + +int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer) { + return c ? (int)static_cast(c)->kv_layer_index(group, layer) : -1; +} int rad_rank(RadCtx* c) { return c ? static_cast(c)->rank() : 0; } int rad_world_size(RadCtx* c) { return c ? static_cast(c)->world_size() : 1; } RadStream rad_stream(RadCtx* c) { return c ? static_cast(c)->stream() : nullptr; } diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp index 44f57716..bb734863 100644 --- a/core/runtime/kvbind.cpp +++ b/core/runtime/kvbind.cpp @@ -1,6 +1,7 @@ /* kvbind.cpp -- see kvbind.h. */ #include "kvbind.h" +#include "kvstream/bind.h" #include "mem/kv.h" namespace rad { @@ -12,6 +13,8 @@ void bind_kv_pools(const Program& p, const std::functionbase; b.layer_stride = gp->layer_stride(); b.bytes = gp->pool_bytes; @@ -34,10 +37,15 @@ void bind_kv_pools(const Program& p, const std::functionn_blocks; + /* `shape[0]` follows the view and is filled by kv_bind_views below: the resident + * window's depth for the ring, the group's context for the prefill stage + * (docs/KV-STREAMING.md §3.1, §4.1). */ + b.shape[0] = gp->pool_blocks(); b.shape[1] = d.n_head_kv; b.shape[2] = gp->block_size; b.shape[3] = 2 * d.head_dim; + /* Both fixed views over the group's one allocation, with the ring active. */ + kv_bind_views(*gp, &b); break; case RAD_KV_LINEAR: b.rank = 4; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 2c36c329..075407c3 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -1,6 +1,7 @@ #include "runtime/tierexec.h" #include "rad_internal.h" +#include "kvstream/plan.h" #include #include @@ -31,12 +32,18 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, for (int32_t g : groups) { const KVGroupPlan* p = kv->plan(g); if (!p || !p->paged()) continue; + /* A streamed group's pool is one layer of its context, so a gather of layer L would copy + * the last staged layer n_layers times. Its mirror is the tier and the residency map + * restores a block on the next resolve (docs/KV-STREAMING.md §4.1). */ + if (!kv_tier_cached(*p)) continue; GroupInfo gi; gi.g = g; gi.n_layers = p->n_layers; gi.frag = p->layer_bytes_per_block(); gi.layer_stride = p->layer_stride(); - gi.n_blocks = p->n_blocks; + /* The pool's depth: a streamed group backs fewer blocks than it addresses, and the tier + * gathers fragments of the blocks that are here (docs/KV-STREAMING.md §3.1). */ + gi.n_blocks = p->pool_blocks(); gi.base = p->base; gi.replicated = p->replicated; if (p->zero) { @@ -109,6 +116,12 @@ int TierExec::slot_layout(const std::vector& ranks, for (int32_t g : groups) { const KVGroupPlan* p0 = ranks[0]->plan(g); if (!p0 || !p0->paged()) continue; + /* A streamed group is not part of a tier entry: its pool is one layer deep, so a gather + * of layer L would copy the last staged layer n_layers times, and its host mirror is the + * tier (docs/KV-STREAMING.md §4.1). TierExec::stage skips the same groups, so this + * arithmetic and its gather offsets agree. A streamed group is never replicated, so + * leaving it out of the replicated window too is the safe rule. */ + if (!kv_tier_cached(*p0)) continue; bool replicated = false; for (size_t i = 0; i < ranks.size(); ++i) { const KVGroupPlan* p = ranks[i]->plan(g); diff --git a/core/runtime/xprefetch.cpp b/core/runtime/xprefetch.cpp index 30198a14..0a2c4bbd 100644 --- a/core/runtime/xprefetch.cpp +++ b/core/runtime/xprefetch.cpp @@ -202,7 +202,7 @@ void Ctx::xp_serve(XpState& x) { if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold); continue; } - if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq) == RAD_OK) { + if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq, 0) == RAD_OK) { ++x.lists; if (r.mark) x.marks.emplace_back(r.mark, x.lists); } else { diff --git a/docs/KERNELS.md b/docs/KERNELS.md index 54f765ab..e6c3c96e 100644 --- a/docs/KERNELS.md +++ b/docs/KERNELS.md @@ -280,6 +280,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout): | `hc_write_bf16` | `hc_write` | | `join_add_scale_bf16` | `join_add_scale` | | `kv_store_bf16` | `kv_store` | +| `kv_store_streamed_bf16` | `kv_store_streamed` | +| `kv_store_streamed_fp8` | `kv_store_streamed` | | `l2norm_chan_bf16` | `l2norm_chan` | | `lane_gather_w32` | `lane_gather` | | `lane_store_w32` | `lane_store` | @@ -313,6 +315,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout): | `qk_norm_rope_gate` | `qk_norm_rope_gate` | | `qk_norm_rope_gate_kv_store_bf16` | `qk_norm_rope_gate_kv_store` | | `qk_norm_rope_gate_kv_store_fp8` | `qk_norm_rope_gate_kv_store` | +| `qk_norm_rope_gate_kv_store_streamed_fp8` | `qk_norm_rope_gate_kv_store_streamed` | +| `qk_norm_rope_gate_kv_store_streamed_bf16` | `qk_norm_rope_gate_kv_store_streamed` | | `qkv_norm_rope_bf16` | `qkv_norm_rope` | | `qsa_block_key_bf16` | `qsa_block_key` | | `qsa_score_bf16` | `qsa_score` | @@ -507,6 +511,7 @@ on a marked row is a hole this model falls into. | `hc_write` | | host | device | host | | `join_add_scale` | | - | device | - | | `kv_store` | yes | host | device | host | +| `kv_store_streamed` | | host | device | host | | `l2norm_chan` | | - | device | host | | `lane_gather` | | - | device | host | | `lane_store` | | - | device | host | @@ -534,6 +539,7 @@ on a marked row is a hole this model falls into. | `qk_norm_rope` | | host | device | host | | `qk_norm_rope_gate` | | - | device | - | | `qk_norm_rope_gate_kv_store` | | - | device | - | +| `qk_norm_rope_gate_kv_store_streamed` | | - | device | - | | `qkv_norm_rope` | | - | device | - | | `qsa_block_key` | | host | device | host | | `qsa_score` | | - | device | host | diff --git a/docs/OPS.md b/docs/OPS.md index 0b851db2..19db01f8 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -851,6 +851,7 @@ as the weight's GEMM stored them and claims no form. It changes no value. | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | | `sam_attn` | `M`(range) `head_dim` `n_head` `grid_h` `grid_w` `window` `scale`:f64 `dtype` | `q`, `k`, `v`, `cu_seqlens`, `out`, `rel_pos_h`w, `rel_pos_w`w | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | +| `kv_store_streamed` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout | | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | @@ -1033,6 +1034,21 @@ declares bound it lower. `RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool base belongs to the block manager, not the batch. +**When the group streams, the pool is a ring and the operand is its layer.** The device pool then +holds `slots` blocks and the sequence's block table still names up to `blocks` ids, so the sparse +path needs one indirection: `kv_resolve` (in "Sparse attention (QSA)") rewrites the selected ids as +ring slots and copies a block in from the pinned host mirror on a miss. Every other op reads the +cache exactly as before, because it is handed a resolved table. + +Such a group is written by `kv_store_streamed` instead of `kv_store`: the token's k and v go into +the host mirror ALWAYS and into the ring slot only when the residency map says the block is +resident. The mirror is the truth; the ring is a cache of it. The order a layer keeps is **store, +then resolve, then attention**, because a block this step writes may not be in the ring yet and the +resolve copies such a block whole out of the mirror. The residency test belongs in the writer, not +only in the resolve: at decode the block a step writes is usually the block the previous step made +resident, so a mirror-only writer would leave the ring's copy of it missing this step's tokens and +the resolve, seeing the block resident, would not copy it. + **`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of `--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an f16 scale (its absmax over the largest code, clamped so every code decodes finite in f16), @@ -1056,7 +1072,39 @@ ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6 gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly representable set and the attention rows to its inline oracle. -### `qk_norm_rope_gate` (device-only) +### `kv_store_streamed` + +`kv_store` for a group whose KV streams: one scatter into the group's two copies instead of one. + +- **`k`, `v`, `slot_mapping`** — as `kv_store`: bf16 activations, an i32 flat slot per token, a + negative slot skipped. `slot / block_size` is the block and `slot % block_size` the position in + it. +- **`host`** — bytes, `[blocks, row]`, inout. The layer's authoritative mirror, one block a row, + the identity layout the design note gives it (`[block, kv_heads, block_size, 2 * head_dim]`, + K then V in a slot). **Written for every token with a slot, always.** +- **`kv_cache`** — the ring, the same `RAD_KV(group, layer)` operand `attn_paged`, `kv_store` and + `kv_resolve` take. **Written at `res[block]` only when that is >= 0.** +- **`res`** — `i32 [blocks]`, in. The residency map `kv_resolve` maintains. Read, never written: + residency is the resolve's decision, so the store cannot move the map under a selection that has + already been resolved. + +Both planes are dense rows of the same byte pitch, so one offset addresses the same element of the +same block in either and the two copies cannot disagree. The conversion follows the cache's dtype: +`kv_store_fp8`'s for E4M3 (divided by the reader's descales) and `kv_store_bf16`'s for bf16 (the +value itself, no descales; every offset is two bytes wide). The rows are `kv_store_streamed_fp8` +and `kv_store_streamed_bf16`, so the default `--kv-cache-dtype bf16` streams as well as fp8; a +packed fp8_v4/k6_v4 group has no streamed row and the engine refuses to stream it rather than leave +it without a writer. + +The caller's order, per layer, is **store → resolve → attention**. A block the current step writes +may not be in the ring at all (a block's first tokens, or a block a previous resolve evicted); the +resolve then copies the whole block out of the mirror, so the store must have written it. A block +that is resident takes the token in both copies, so the ring never holds a stale block and the +resolve never needs to re-copy a resident one. A map entry outside `[-1, slots)` is a state fault +that libref refuses; the device kernel treats it as not resident, which writes the mirror and lets +the resolve refuse the step. + + | op | params | operands | |---|---|---| @@ -1078,6 +1126,7 @@ rank-2 view can express, which would otherwise take `heads` `rmsnorm` launches p | op | params | operands | |---|---|---| | `qk_norm_rope_gate_kv_store` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout | +| `qk_norm_rope_gate_kv_store_streamed` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout | **`qk_norm_rope_gate_kv_store`** is the prologue followed by `kv_store` in one launch: each k head's block already holds its token's rotated k one element a lane, so it also writes that element and @@ -1094,6 +1143,25 @@ accepts, but a rotated element is a difference of two products, so where those n ULP becomes a few percent and the transcript moves within a few dozen steps. The kernel reproduces the reference's fold exactly: widths above the head dim contribute zeros, and adding 0.0f is exact. +**`qk_norm_rope_gate_kv_store_streamed`** is that fold for a group whose KV streams: the store is +`kv_store_streamed` instead of `kv_store`, so it takes the residency map and the group's host +mirror as its last two operands. The token's rotated k and its v go into the mirror's block row for +every token with a slot, and into `kv_cache[res[block]]` only where the map calls the block +resident; a negative or out-of-range slot stores nothing, and a map entry outside `[-1, slots)` is +treated as not resident (libref refuses it as a state fault, and the resolve then refuses the +step). Both planes are the same dense row of the same paged layout, and the rotated k is the value +`k_out` receives, so the bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. It has +an E4M3 row (`_fp8`) and a bf16 row (`_bf16`, the default cache dtype; the two planes hold the +rotated k and v themselves, two bytes wide). It +exists because the pair costs a launch a layer on the decode path: one launch where the unfused +prologue and the store were two, and one fewer hop between store, resolve and attention. + +The caller's order is unchanged -- **store, then resolve, then attention** -- and a staged pass +keeps the stage-copy wait before the store, which is now the prologue's own write. The folded path +takes the same guards as the hosted one: `T` at or below the fused rows and a pass at one rotary +component per token (no mixed media positions). Where the row is absent, or a pass declines it, the +layer runs `qk_norm_rope_gate` plus a separate store exactly as before. + ## Image generation The ops a diffusion image generator declares (`rad_declare_generator`, `abi/rad_builder.h`): a @@ -2673,13 +2741,15 @@ order, not a slow one. | `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | | `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | +| `kv_resolve` | `M`(range) `blocks` `slots` `sel_pitch` `block_bytes` | `sel`:inout, `nsel`, `res`:inout, `slot_block`:inout, `slot_state`:inout, `ctl`:inout, `host`, `kv_cache`:inout | | `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | | `qsa_work` | `M`(range) `n` `ratio` `ring` `seqs` `work` `dtype` | `k`, `pos`, `cu`, `state`, `sidx`, `bt`, `rope`? → `stage`, `page`, `bpos`, `nc` | Five ops decompose one indexer, which scores blocks of key history against the query and hands `attn_paged` a shorter block table. `docs/QSA.md` describes the decomposition and `arch/common/rad_qsa.h` issues all five. libref implements all five (the oracle for libr4d's -kernels), and libavx all five for the host path. +kernels), and libavx all five for the host path. `kv_resolve` sits between the last of them and the +attention when the group's KV streams; it is described below, after `qsa_select`. ### `qsa_block_key` @@ -2808,6 +2878,124 @@ because a chunk's local top-k contains every global top-k member of that chunk, output layout too: the attention sums the selected pages in table order and float addition is not associative. Without scratch, or above 32 rows, one workgroup per query walks the whole list. +### `kv_resolve` + +Turns `qsa_select`'s block ids into the ring slots that hold them, and copies a block in when it is +not resident. It is the one op a streamed KV group needs: `sel` is the only place the sparse path +names KV storage, because `qsa_select` already writes `tb[b]`, the group's pool page id, and +`attn_paged` uses each entry as a raw pool index. When the group streams, the device pool is +`slots` blocks deep and the id space is `blocks`, so an id is no longer an address; after this op +every entry is a slot of `kv_cache` and the attention is unchanged. + +The layouts, which the schema cannot state (the maps are one format, and the two block planes are +bytes, so the op is the same code at every cache layout). The shape given is the operand's extent: + +- **`sel`** — `i32 [M, sel_pitch]`, inout. In: block ids. Out: the ring slot holding each block, for + the entries below `nsel[q]`; the -1 padding of `qsa_select` past them is untouched. +- **`nsel`** — `i32 [M]`, in. The valid entries of each row, as `qsa_select` wrote them. +- **`res`** — `i32 [blocks]`, inout. Block id -> slot, or -1 absent; -2 is a claim this call has made + and never leaves it behind. +- **`slot_block`** — `i32 [slots]`, inout. Slot -> block id, or -1 free. +- **`slot_state`** — `i32 [slots, 2]`, inout. Column 0 is the epoch that last used the slot, column 1 + a two-bit **heat counter** in `[0, 3]`: bumped by one, clamped at 3, on every use (a hit or a + placement, once a slot a call), and halved when the sweep passes the slot. 31 bits of the i32 are + unused, so the policy needs no new field and no ABI change. +- **`ctl`** — `i32 [16]`, inout. `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call, + `[3]` overflow (latched), then `u64` misses, lookups and calls from `[4]`, 8-byte aligned, then + `[10]` the largest selection union one call has seen (distinct blocks, hits plus misses), `[11]` + the largest number of blocks one call has placed, and `[12]` the largest number of distinct + blocks one call has claimed — the depth its miss list had to hold. The maxima are the measurement + a ring and a claim list are sized from: `[10]` against the ring's depth says whether one launch + can overflow it, `[12]` against `max_seqs * sel_pitch` says whether a claim list is wide enough. +- **`host`** — bytes, `[blocks, block_bytes]`, in. The layer's authoritative mirror, identity block + layout: block `b` at `b * block_bytes`, exactly as the design note lays it out. +- **`kv_cache`** — bytes, `[slots, block_bytes]`, inout. The layer's ring, the same operand + `attn_paged` and `kv_store` take as `RAD_KV(group, layer)`. + +One call, in order: bump the epoch, one lookup per distinct block, one victim per miss, re-point +both maps, copy each missed block, rewrite every valid selection entry. What each step owes: + +- **One call is one epoch.** The epoch is bumped first; a resident block takes the new epoch and + bumps its heat counter, so the sweep can tell what this call has already touched from what it may + take. +- **One lookup per distinct block, and the map is its own set.** A miss is claimed once, `-1` to + `-2`, so a block named by several rows is claimed by the first of them. `sel` entries past + `nsel[q]` are `-1` padding and are not touched; `nsel[q]` above `sel_pitch` is refused rather than + steered into the neighbouring row. +- **The miss list is in ascending block id, and that is part of the contract.** First-appearance + order would let the row that claimed a block first decide which slot it lands in, so two + implementations of one contract would produce different tables. Ascending is a fact about the + claim set, not about the map: a device launch sorts the claims it made, or — above the shared + claim list — collects the smallest `slots` of them a window of the id space at a time, both over + the selection's entries. `blocks` is the id space (`max_seqs * ceil(max_ctx / block_size)`, 102 400 + at the parity shape) and never the size of one launch, so nothing here walks it. +- **The claim list's depth is derived, not a constant.** One claim is one distinct absent block a + selection entry names, so a launch makes at most `M * sel_pitch` of them (and at most `lookups`, + which is `sum_q nsel[q]`). The device kernel sizes its shared list at + `next_pow2(min(M * sel_pitch, the workgroup's LDS room))`, so any `--max-num-seqs` follows from the + operands: `max_seqs * 513` is 2052 at four sequences, 4104 at eight. There is no cap to raise and + none to fall off, and `ctl[12]` reports the largest count a launch has made. +- **The victim rule is the block's own slot if it is free, then a free slot, then CLOCK, from a hand + that ends just past the last slot taken, with second chance.** A miss whose id is inside the ring + and whose own slot is free goes to slot `b`, so while the context is shorter than the ring the map + is `res[b] = b` and adjacent block ids land in adjacent slots of one layer's stripe, which is the + order the attention's gather reads them in. That is placement only: it takes a slot only when + that slot is free and it does not move the hand, so it never evicts, and a miss it cannot place + falls through to the walk below from the hand it would always have seen -- at depth, where most ids + are past `slots`, the same blocks land in the same slots as before. A free slot holds no block, so + taking it costs nothing and it is claimed before any resident block is considered; the ring's empty + region fills before an eviction. + A slot this call already used (a hit's, or a miss's already claimed) is passed and keeps its + heat counter, free or not; when a whole turn finds no free slot, the sweep halves the counter of a + warm slot (`old >> 1`) and passes it, and takes a cold one (counter 0). The hand still **picks** + the victim -- a per-visit decision, not a search -- so the policy costs no reduction, no barrier + and no extra traffic: an add-and-clamp in place of a constant store and a shift in place of a + zero. That is why it is affordable where an exact LRU is not: the epoch-ordered minimum needs a + collective reduction per miss, which costs more than the choice is worth. The free scan halves no + counter and leaves the hand alone when it finds nothing, so a ring with no free slot takes exactly + the victim the sweep names. Every write clamps the counter to 3, + so two passes halve any value to 0 and the third places the miss: a sweep visits at most + `3 * slots` slots. The counter is the same decayed-use-count mechanism the streamed experts + already replace by (`core/place/heat.*`), at ring granularity. +- **The ring must hold the union of one call's selection.** A hit holds a slot and a miss needs + another, so `hits + misses <= slots` is the sizing rule. What that union is depends on the launch: + a decode step takes the ring and a prefill step takes the one-layer stage, and a decode step issues + one row a sequence (`1 + n_spec` rows a sequence under speculation), so at most + `max_seqs * (1 + n_spec) * (topk + 1)` blocks -- which is the ceiling `--kv-resident` is held to at + startup, and `ctl[10]` is what says at run time that the bound held. Overflow is not silent: an unplaced miss reverts to `-1` (so a later call may claim it) + and its selection entries are rewritten to slot 0 -- a defined address inside the ring, because a + block id is an address past it that the attention dereferences unchecked -- with `ctl[3]` latched. + A caller that finds `ctl[3]` set must discard the step: those entries do not name their blocks, so + the launch's output is wrong by construction and is never served. +- **The copied bytes are the mirror's bytes.** One `memcpy` per placed miss, `block_bytes` long, + nothing converted, so a streamed block is bit-identical to what the writer put in the mirror. + That is why `block_size` is not a parameter and `block_bytes` is: the op never reads an element, + and a `block_size` key would make it a KV group's consumer, taking the block size the block + manager reads away from the resolved attention kernel. +- **`slots` is the operand's, not only the parameter's.** `slot_block`'s extent is the ring a call + may address, exactly as `sel`'s extent states `M` and its row pitch states `sel_pitch`; the declared + parameter is the ceiling a call may not pass. The pool is planned after the program is built, so a + ring the engine sized smaller (`--kv-resident`, when it streams at all) reaches the op as a + shorter operand. The declared ceiling is the ring the deployment carves -- `--kv-resident` in + tokens rounded up to whole blocks, clamped to the group's context (`RadBuildCtx:: + kv_resident_blocks`) -- and not the block-id space `blocks`, so the geometry an engine reports for + this op is the ring it is issued with; with nothing streaming the two are equal. The ceiling also + sizes the row's scratch. +- **The miss list is scratch, not an operand.** It is one launch's temporary; a device row declares + `next_pow2(slots) + slots` i32s through its scratch hook (the miss list, then the slots it pairs + with) and the reference needs none. The claim list before the sort is dynamic LDS, not scratch, + while it fits: the sort reads every element from every thread, so it belongs in the workgroup, and + the row sizes that launch's LDS from the bound above. A launch too wide for that room sorts the + list in the scratch's first plane, which is why it is padded to a power of two. +- **The op is stateful, and therefore not concurrent.** epoch, hand, heat counters and counters + live between launches, so the row must not carry `rad_kernel_concurrent` + (`abi/rad_abi.h:493`); without the promise the engine orders the launch behind everything before + it, which is what the map needs. It is still recordable: the maps, the ring and the mirror are + fixed-size from the group's declaration, so addresses and pitches never move and a replay is + valid. +- **The caller brings the state up.** `res` and `slot_block` filled with `-1`, `slot_state` and + `ctl` zeroed. There is no reset op: a residency map lives as long as its pool. + ### `qsa_tail_store` Parks the raw index keys of the tokens that have not completed a block yet: diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 7fa41a55..34b7b2de 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -46,6 +46,7 @@ set(AVX_KERNEL_SRC avx_planes.cpp avx_lora.cpp avx_attn.cpp + avx_kvstream.cpp avx_sam_attn.cpp avx_qsa.cpp avx_moe.cpp diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index c6bd6598..2c8b4b32 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -1060,6 +1060,102 @@ AVX_KERNEL(kv_store) { return RAD_OK; } +/* ------------------------------------------------------------------ kv_store_streamed */ +/* kv_store for a group whose KV streams: the host mirror is authoritative and the ring is a cache + * of it. `host` is written ALWAYS, at the block's identity row; `kv_cache[res[block]]` only when + * the residency map says the block is resident. libref/ref_attn.cpp (ref_kv_store_streamed) states + * why the residency test belongs in the writer and not in the resolve: at decode the block a step + * writes is usually already resident, so a mirror-only writer would leave the ring's copy of it + * short of this step's tokens and the resolve would not re-copy a resident block. + * + * The two planes are the same bytes in the same paged layout, so one conversion writes both: the + * mirror is a view of the same `[block, kv_heads, block_size, 2 * head_dim]` shape whose dtype is + * the cache's, so the two copies cannot round differently. E4M3 converts as kv_store_fp8 does; + * bf16 stores the value itself, as kv_store_bf16 does. `res` is read, never written. */ +AVX_KERNEL(kv_store_streamed) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3]; + const RadTensor *res = &a->t[4], *host = &a->t[5]; + + const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0); + const int64_t block_size = p_int(a, "block_size", 0); + const int64_t kv_heads = p_int(a, "n_head_kv", 0); + if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE; + if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE; + if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE; + if (host->dtype != RAD_U8) return RAD_E_DTYPE; + /* E4M3 (the fp8 QSA family) or bf16 (the default cache dtype); a packed fp8_v4/k6_v4 group has + * no streamed row. */ + const bool fp8 = kv->dtype == RAD_F8E4M3; + if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED; + if (kv->rank != 4 || kv->shape[1] != kv_heads || kv->shape[2] != block_size || + kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE; + if (host->rank != 2) return RAD_E_SHAPE; + + /* One block of one layer: both planes are dense rows of it, so the same offsets address the + * same element of the same block in either. */ + const int64_t EB = fp8 ? 1 : 2; + const int64_t row = kv_heads * block_size * 2 * head_dim * EB; + const int64_t slots = kv->shape[0], blocks = host->shape[0]; + if (host->shape[1] != row || + host->stride[0] * rad_dtype_bytes(host->dtype, 1) != row) return RAD_E_STRIDE; + if (kv->stride[0] * rad_dtype_bytes(kv->dtype, 1) != row) return RAD_E_STRIDE; + if (slots <= 0 || blocks <= 0) return RAD_E_SHAPE; + if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE; + + const int64_t M = numel(sm); + if (M <= 0 || numel(k) < M * kv_heads * head_dim || + numel(v) < M * kv_heads * head_dim) return RAD_E_SHAPE; + + const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1; + const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds; + const int64_t k_rs = row_stride(k, kv_heads * head_dim); + const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1; + const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds; + const int64_t v_rs = row_stride(v, kv_heads * head_dim); + const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f; + const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f; + + /* Refused before the first write, exactly as libref refuses it: a half-written mirror makes + * the next step's copies plausible and wrong. (The device row cannot return a host status from + * inside its kernel and guards these instead; a legal call never takes either path.) */ + const int32_t* const R = (const int32_t*)res->data; + for (int64_t t = 0; t < M; ++t) { + const int64_t slot = ldi(sm, offlin(sm, t)); + if (slot < 0) continue; + const int64_t blk = slot / block_size; + if (blk >= blocks) return RAD_E_SHAPE; + if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL; + } + + RadTensor hkv = *host; + hkv.dtype = kv->dtype; /* the same bytes, seen as the cache's dtype */ + const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads); + const KVView hv = kv_view(&hkv, head_dim, block_size, kv_heads); + + AVX_PARALLEL_FOR_IF(M * kv_heads * head_dim >= AVX_PAR_MIN) + for (int64_t t = 0; t < M; ++t) { + const int64_t slot = ldi(sm, offlin(sm, t)); + if (slot < 0) continue; + const int64_t blk = slot / block_size, off = slot % block_size; + const int64_t hb = blk * hv.sb + off * hv.so; + const int64_t cb = R[blk] >= 0 ? R[blk] * kvv.sb + off * kvv.so : -1; + for (int64_t h = 0; h < kv_heads; ++h) { + for (int64_t d = 0; d < head_dim; ++d) { + const float xk = ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks; + const float xv = ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs; + stt(&hkv, hb + h * hv.sh + d * hv.sd, xk); + stt(&hkv, hb + h * hv.sh + (head_dim + d) * hv.sd, xv); + if (cb >= 0) { + stt(kv, cb + h * kvv.sh + d * kvv.sd, xk); + stt(kv, cb + h * kvv.sh + (head_dim + d) * kvv.sd, xv); + } + } + } + } + return RAD_OK; +} + /* ================================================================== rotary * * NeoX pairs element i with i + rotary_dim/2; GPT-J ("interleaved") pairs 2i with 2i+1. The style diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e2293ae8..84bf99b6 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -429,6 +429,22 @@ std::vector build_cases() { add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2), HI("block_size", 16), HS("kv_dtype", "fp8_e4m3"), HF("k_scale", ks), HF("v_scale", 1.0 / ks) }); + /* The streamed store, on one block and one ring slot (see ref_shapes.cpp: a described map + * cannot be an injective permutation, so a multi-block call could draw two blocks one slot). + * The resident/mirror-only split is built by hand in avx_check_hand.cpp. */ + for (double ks : { 1.0, 0.5 }) + add("kv_store_streamed", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2), + HI("block_size", 32), HS("kv_dtype", "fp8_e4m3"), + HF("k_scale", ks), HF("v_scale", 1.0 / ks) }); + add("kv_store_streamed", { HI("M", 3), HI("head_dim", 32), HI("n_head_kv", 1), + HI("block_size", 4), HS("kv_dtype", "fp8_e4m3") }); + /* The same store into a bf16 cache: both planes are the values themselves, two bytes wide. */ + for (double ks : { 1.0, 0.5 }) + add("kv_store_streamed", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2), + HI("block_size", 32), HS("kv_dtype", "bf16"), + HF("k_scale", ks), HF("v_scale", 1.0 / ks) }); + add("kv_store_streamed", { HI("M", 3), HI("head_dim", 32), HI("n_head_kv", 1), + HI("block_size", 4), HS("kv_dtype", "bf16") }); for (const char* mode : { "neox", "gptj" }) { add("rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2), HF("theta", 10000.0), HF("scale", 1.0), HS("mode", mode), @@ -528,6 +544,22 @@ std::vector build_cases() { HS("dtype", "f32") }); add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3), HI("work", 3), HS("dtype", "f32") }); + /* The streamed group's residency map at a decode step's geometry and at the edges a check can + * describe: a ring shallower than the id space and deeper than it, one query row, a pitch of + * one, and a `block_bytes` that is not a multiple of a vector (a block is a whole number of + * 16-byte lanes in practice, but nothing in the schema says so and the copy's tail must still + * be right). libref describes the map as every block resident (ref_shapes.cpp), so these cases + * exercise the epoch, the hit stamp, the rewrite and the bookkeeping; a miss, an eviction, a + * second chance and an overflow need a cold map, which no description draws, and are built by + * hand in avx_check_hand.cpp. */ + add("kv_resolve", { HI("M", 4), HI("blocks", 300), HI("slots", 96), HI("sel_pitch", 33), + HI("block_bytes", 256) }); + add("kv_resolve", { HI("M", 6), HI("blocks", 64), HI("slots", 128), HI("sel_pitch", 17), + HI("block_bytes", 24) }); + add("kv_resolve", { HI("M", 1), HI("blocks", 8), HI("slots", 4), HI("sel_pitch", 1), + HI("block_bytes", 8) }); + add("kv_resolve", { HI("M", 3), HI("blocks", 1), HI("slots", 1), HI("sel_pitch", 513), + HI("block_bytes", 4096) }); /* The proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the * frequency denominator is head_dim. */ for (const char* mode : { "neox", "gptj" }) { @@ -1232,6 +1264,15 @@ std::vector build_cases() { (double)M * blocks * 8, 0); speed("qsa_select", { HI("M", 2048), HI("blocks", 16384), HI("topk", 512), HI("ratio", 4), HI("seqs", 1) }, 2048.0 * 16384 * 8, 0); + /* The residency map at a decode step: an 8K-block id space over a 2048-slot ring (a group at + * depth 3 with 256-token blocks), one query row and a four-row verify window, 512 selected + * blocks a row. libref describes the map all-resident, so this times the two selection passes, + * the compaction of the claim list, the rewrite and the bookkeeping; the block copies are one + * per miss, and which blocks miss is a cache state the geometry does not carry. */ + for (const int64_t M : { 1, 4 }) + speed("kv_resolve", { HI("M", M), HI("blocks", 8192), HI("slots", 2048), + HI("sel_pitch", 513), HI("block_bytes", 2048) }, + (double)M * 513 * 8, 0); /* The tail and the work list: four decoding sequences, and a prefill chunk's volume (512 * sequences of four rows each completing a block, 2048 key rows staged). */ speed("qsa_tail_store", { HI("M", 4), HI("n", 128), HI("ratio", 4), HI("ring", 7), diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 06bfd340..5ff8adb3 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -57,6 +57,11 @@ struct Hand { int oracle_opd = -1; std::vector oracle; double oracle_tol = 0; + /* An answer neither library computes: operand `oracle_opd`'s whole buffer must hold these + * bytes on both sides. For a case whose bytes follow from the layout by hand, so a store that + * writes the right values to the wrong place fails even when both libraries agree. */ + int want_raw_opd = -1; + std::vector want_raw; Hand(const char* n, const char* o, double t) : name(n), op(o), tol(t) {} @@ -159,6 +164,13 @@ struct Hand { return *this; } + /* Operand `opd` (an output) must hold `bytes` verbatim on both sides. */ + Hand& expect_bytes(int opd, std::vector bytes) { + want_raw_opd = opd; + want_raw = std::move(bytes); + return *this; + } + enum Result { PASS, FAIL, ABSENT }; Result fail(const std::string& why) { @@ -275,6 +287,26 @@ struct Hand { } } } + if (want_raw_opd >= 0) { + const Buf& bf = bufs[(size_t)buf_of[(size_t)want_raw_opd]]; + if (want_raw.size() != bf.orig.size()) { + fail("the expected bytes are " + std::to_string(want_raw.size()) + ", the operand " + + std::to_string(bf.orig.size())); + ok = false; + } else { + for (int side = 0; side < 2; ++side) { + const uint8_t* d = side ? bf.b.data() : bf.a.data(); + size_t at = 0; + while (at < want_raw.size() && d[at] == want_raw[at]) ++at; + if (at != want_raw.size()) { + std::printf(" FAIL %-20s %s\n %s byte %zu is 0x%02x, expected 0x%02x\n", + op.c_str(), name.c_str(), side ? who : "libref", at, d[at], + want_raw[at]); + ok = false; + } + } + } + } double core_rel = -1; if (oracle_opd >= 0 && !oracle.empty()) { const Buf& bf = bufs[(size_t)buf_of[(size_t)oracle_opd]]; @@ -3136,6 +3168,449 @@ void qsa_cases(std::vector& hs) { } } +/* ================================================================== the streamed KV residency map + * + * `kv_resolve`'s service shapes: a partly resident pool, an eviction, a second chance over the + * two-bit heat counter (including the cases where it must differ from a one-bit CLOCK), an + * overflow, one claim for a block several rows name, a copy whose length is not a vector multiple, + * and the state faults it refuses. libref's description can only draw an all-resident map (a cold + * entry is -1, which no index draw expresses), so every case below is one the table cannot reach. + * + * The pool starts as the maps say it is: a slot holding block `b` carries b's bytes and a free + * slot carries 0xEE, the marker tests/ref_test.cpp uses. Then the copies are visible element by + * element, and both libraries are compared over the whole of every map, the mirror's bytes and the + * ring. */ +namespace kvhand { + +enum { kNOB = 0xEE }; + +/* The bytes block `b`, element `i` of its block: a pattern under 256 whose block digit is + * recoverable, so a copy that landed in the wrong slot shows. */ +float block_byte(int64_t b, int64_t i) { return (float)((29 * b + i) & 0xff); } + +/* A pool with its operands in the contract's order. `sel` and `sst` are flat, shaped here. */ +Hand pool(const char* name, int64_t M, int64_t blocks, int64_t slots, int64_t pitch, + int64_t bbytes, std::vector sel, std::vector nsel, + std::vector res, std::vector sblk, std::vector sst, + std::vector ctl) { + Hand h(name, "kv_resolve", 0.0); + h.dense(RAD_I32, { M, pitch }, + [sel](int64_t i) { return (float)sel[(size_t)i]; }, true) + .idx(nsel) + .idx(res, true) + .idx(sblk, true) + .dense(RAD_I32, { slots, 2 }, + [sst](int64_t i) { return (float)sst[(size_t)i]; }, true) + .idx(ctl, true) + .dense(RAD_U8, { blocks, bbytes }, + [bbytes](int64_t i) { return block_byte(i / bbytes, i % bbytes); }) + /* A slot's contents are the block `slot_block` says it holds; a free slot is the marker. */ + .dense(RAD_U8, { slots, bbytes }, + [sblk, bbytes](int64_t i) { + const int64_t b = sblk[(size_t)(i / bbytes)]; + return b < 0 ? (float)kNOB : block_byte(b, i % bbytes); + }, + true) + .pi("M", M).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch) + .pi("block_bytes", bbytes); + return h; +} + +} /* namespace kvhand */ + +void kv_cases(std::vector& hs) { + using namespace kvhand; + + /* Blocks 2 and 5 are resident; the selection names them, then 6 and 4. The epoch reaches both + * hit slots, the misses are claimed once each and placed in ascending block order (4 then 6), + * not in the order the rows name them. Pinned to the rule, so both libraries are held to it + * and not only to each other. */ + { + Hand h = pool("hits take the epoch, misses land in block order", 2, 8, 4, 4, 8, + { 2, 5, 6, -1, 2, 4, -1, -1 }, { 3, 2 }, + { -1, -1, 0, -1, -1, 3, -1, -1 }, { 2, -1, -1, 5 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 0, 3, 2, -1, 0, 1, -1, -1 }); + hs.push_back(std::move(h)); + } + /* An unreferenced resident slot is the victim and the block it held leaves the map; the hand + * starts on it, so the sweep takes it first. */ + { + Hand h = pool("an unreferenced slot is the victim and its block is unmapped", 1, 8, 4, 1, + 4, { 0 }, { 1 }, { -1, 0, 1, 2, 3, -1, -1, -1 }, { 1, 2, 3, 4 }, + { 0, 1, 0, 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 1 }); + hs.push_back(std::move(h)); + } + /* A free slot is taken before an unreferenced resident slot, even when the hand starts on the + * resident one: the empty region is not a victim and the block in that slot stays. */ + { + Hand h = pool("a free slot is taken before an unreferenced one", 1, 8, 4, 1, 4, { 0 }, { 1 }, + { -1, -1, -1, 0, -1, -1, -1, -1 }, { 3, -1, -1, -1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 1 }); + hs.push_back(std::move(h)); + } + /* Second chance: every slot is referenced, so a full turn clears every bit and the miss takes + * the slot the hand started on. The bits the sweep passed stay cleared. */ + { + Hand h = pool("a referenced slot gets a second chance", 1, 8, 4, 2, 4, { 0, 1 }, { 2 }, + { -1, -1, -1, -1, 0, 1, 2, 3 }, { 4, 5, 6, 7 }, + { 0, 1, 0, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 0, 1 }); + hs.push_back(std::move(h)); + } + /* The heat counter, and the three shapes that separate it from a one-bit CLOCK. Slot 0 was hit + * on two earlier calls (counter 2), slots 1 and 2 once each: a CLOCK sweep clears all three bits + * and evicts slot 0 on its second pass, while 2 -> 1 -> 0 leaves slot 0 resident and takes slot + * 1. Pinned to the victim, so both libraries are held to the rule and not only to each other. */ + { + Hand h = pool("a slot hit twice survives two sweep passes", 1, 32, 3, 1, 8, { 20 }, { 1 }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, + { 10, 11, 12 }, { 0, 2, 0, 1, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 1 }); + hs.push_back(std::move(h)); + } + /* The halving is only visible in `slot_state`, not in the victim (a cold slot 1 is taken either + * way), so this case pins the counter: a saturated 3 is 1 after one pass, not the 0 a one-bit + * CLOCK would leave. */ + { + Hand h = pool("a saturated counter halves 3 -> 1 on one pass", 1, 32, 3, 1, 8, { 20 }, { 1 }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, + { 10, 11, 12 }, { 0, 3, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(4, { 0, 1, 1, 1, 0, 0 }); + hs.push_back(std::move(h)); + } + /* A saturated counter (3) against three slots placed on the previous call (1 each): the sweep + * walks two full laps, spends the fresh counters first, and takes slot 1. CLOCK, for which all + * four are "referenced", takes slot 0 -- the hottest block in the ring. */ + { + Hand h = pool("a saturated counter outlasts a fresh placement", 1, 32, 4, 1, 8, { 20 }, + { 1 }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, + { 10, 11, 12, 13 }, { 0, 3, 0, 1, 0, 1, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 1 }); + hs.push_back(std::move(h)); + } + /* One bump a slot a call: block 10 is resident and named by both entries, so its counter goes + * 1 -> 2. A per-entry bump would leave 3, which is the disagreement this case exists for. */ + { + Hand h = pool("a block two rows name gains one step of heat", 1, 32, 3, 2, 8, { 10, 10 }, + { 2 }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, + { 10, 11, 12 }, { 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(4, { 1, 2, 0, 0, 0, 0 }); + hs.push_back(std::move(h)); + } + + /* Overflow: three hits hold slots 0..2 and two misses want the one slot left. The first is + * placed, the second has nowhere and must not steal the slot the first took - every slot of + * the ring is stamped with this call's epoch - so it reverts to -1 and its entry keeps the + * block id, a value that is not a slot. */ + { + Hand h = pool("an unplaceable miss latches overflow, never a used slot", 1, 8, 4, 5, 4, + { 6, 7, 0, 1, 2 }, { 5 }, { 0, 1, 2, -1, -1, -1, -1, -1 }, { 0, 1, 2, -1 }, + { 0, 1, 0, 1, 0, 1, 0, 0 }, { 0, 3, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 3, 0, 0, 1, 2 }); + hs.push_back(std::move(h)); + } + /* A block two rows name is claimed once, the list is ascending, a row of zero entries resolves + * nothing, and `block_bytes` 24 leaves the copy a tail shorter than a vector lane group. + * Placement: 4 fits the ring and takes slot 4, while 9 and 15 are past `slots` and take the + * first free slots from the hand (0 then 1). */ + { + Hand h = pool("one claim per block, a 24-byte copy, an empty row", 3, 16, 6, 4, 24, + { 9, 4, -1, -1, 9, 15, -1, -1, -1, -1, -1, -1 }, { 2, 2, 0 }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, + { -1, -1, -1, -1, -1, -1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 0, 4, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1 }); + hs.push_back(std::move(h)); + } + /* An epoch is only ever compared for equality (docs/OPS.md), so a stamp that happens to equal + * the epoch this call takes reads as this call's own: the sweep passes that slot and takes the + * next. Nothing is validated about a stamp, and both implementations must read it the same + * way. */ + { + Hand h = pool("a stamp equal to the new epoch is passed", 1, 8, 4, 2, 4, { 0 }, { 1 }, + { -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, -1, -1, -1 }, + { 2, 1, 0, 0, 0, 0, 2, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }); + h.expect(0, { 1 }); + hs.push_back(std::move(h)); + } + + /* 2052 claims -- four rows of 513, which is what `--max-num-seqs 4` selects, and eight more than + * the largest fixed list can hold. Every slot is free, so all 2052 are placed: ids 100..2099 + * take their own slot and the 52 past the ring (2100..2151) take the first free slots from the + * hand, which are 0..51. Pinned, so both libraries are held to the placement and not only to + * each other. The claim list is gathered from the selection, so the id space (`blocks`) is not + * in the cost. */ + { + const int64_t M = 4, blocks = 4096, slots = 2100, pitch = 513, bbytes = 8, first = 100; + std::vector sel, nsel((size_t)M, 513), res((size_t)blocks, -1), + sblk((size_t)slots, -1), sst((size_t)(slots * 2), 0), ctl(16, 0), + want((size_t)slots, -1); + for (int64_t q = 0; q < M; ++q) + for (int64_t i = 0; i < 513; ++i) sel.push_back(first + q * 513 + i); + for (int64_t k = 0; k < 2052; ++k) { + const int64_t b = first + k; + want[(size_t)(b < slots ? b : b - slots)] = b; + } + Hand h = pool("2052 claims: identity below the ring, the rest from the hand", M, blocks, + slots, pitch, bbytes, sel, nsel, res, sblk, sst, ctl); + h.expect(3, want); + hs.push_back(std::move(h)); + } + /* More claims than the ring, and more than a fixed list holds: 12 distinct blocks and 8 slots, + * so the eight smallest ids are placed and the four largest revert to -1 with the + * overflow latched. 1, 2, 3, 5 and 7 fit the ring and take their own slots; 9, 11 and 100 are + * past it and take the first free slots from the hand, 0, then past the identity slots, 4 and + * 6. The claim list cannot be clipped at the ring's depth -- the order the sweep takes is the + * ascending order of the whole claim set. */ + { + Hand h = pool("12 claims in 8 slots place the eight smallest", 1, 4096, 8, 12, 8, + { 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 }, { 12 }, + std::vector((size_t)4096, -1), std::vector((size_t)8, -1), + std::vector((size_t)16, 0), std::vector(16, 0)); + h.expect(3, { 9, 1, 2, 3, 11, 5, 100, 7 }); + hs.push_back(std::move(h)); + } + + /* ---- the refusals: state faults and a selection that does not fit, before any write ---- */ + const std::vector res_ok = { -1, -1, -1, -1, -1, -1, -1, -1 }; + const std::vector sblk_ok = { -1, -1, -1, -1 }; + const std::vector sst_ok = { 0, 0, 0, 0, 0, 0, 0, 0 }; + const std::vector ctl_ok = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + { + Hand h = pool("a block id past the id space is refused", 1, 8, 4, 2, 4, { 8, -1 }, { 1 }, + res_ok, sblk_ok, sst_ok, ctl_ok); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + { + Hand h = pool("more entries than the row holds is refused", 1, 8, 4, 2, 4, { 1, 1 }, { 3 }, + res_ok, sblk_ok, sst_ok, ctl_ok); + h.refuses(RAD_E_SHAPE); + hs.push_back(std::move(h)); + } + { + Hand h = pool("a claim in flight on entry is a state fault", 1, 8, 4, 2, 4, { 1, -1 }, { 1 }, + { -1, -2, -1, -1, -1, -1, -1, -1 }, sblk_ok, sst_ok, ctl_ok); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + { + Hand h = pool("a hand past the ring is a state fault", 1, 8, 4, 2, 4, { 1, -1 }, { 1 }, + res_ok, sblk_ok, sst_ok, + { 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + { + Hand h = pool("a slot_block past the id space is a state fault", 1, 8, 4, 2, 4, { 1, -1 }, + { 1 }, res_ok, { 8, -1, -1, -1 }, sst_ok, ctl_ok); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + /* The mirror's row pitch is not `block_bytes`: a copy would move a block over its neighbour. */ + { + const int64_t blocks = 8, slots = 4, pitch = 2, bbytes = 4, stride = bbytes + 4; + Hand h("a mirror row pitch that is not block_bytes is refused", "kv_resolve", 0.0); + h.dense(RAD_I32, { 1, pitch }, [](int64_t i) { return i == 0 ? 1.0f : -1.0f; }, true) + .idx({ 1 }) + .idx(res_ok, true).idx(sblk_ok, true) + .dense(RAD_I32, { slots, 2 }, [](int64_t) { return 0.0f; }, true) + .idx(ctl_ok, true) + .view(RAD_U8, { blocks, bbytes }, { stride, 1 }, blocks * stride, + [bbytes](int64_t i) { return (float)((29 * (i / stride) + i % bbytes) & 0xff); }) + .dense(RAD_U8, { slots, bbytes }, [](int64_t) { return (float)kNOB; }, true) + .pi("M", 1).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch) + .pi("block_bytes", bbytes) + .refuses(RAD_E_STRIDE); + hs.push_back(std::move(h)); + } + /* A ring shallower than `slots` blocks is refused before the sweep could walk past it. */ + { + const int64_t blocks = 8, slots = 4, pitch = 2, bbytes = 4; + Hand h("a ring with fewer blocks than slots is refused", "kv_resolve", 0.0); + h.dense(RAD_I32, { 1, pitch }, [](int64_t i) { return i == 0 ? 1.0f : -1.0f; }, true) + .idx({ 1 }) + .idx(res_ok, true).idx(sblk_ok, true) + .dense(RAD_I32, { slots, 2 }, [](int64_t) { return 0.0f; }, true) + .idx(ctl_ok, true) + .dense(RAD_U8, { blocks, bbytes }, [bbytes](int64_t i) { return block_byte(i / bbytes, + i % bbytes); }) + .dense(RAD_U8, { slots - 1, bbytes }, [](int64_t) { return (float)kNOB; }, true) + .pi("M", 1).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch) + .pi("block_bytes", bbytes) + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(h)); + } +} + +/* ================================================================== the streamed KV store + * + * `kv_store_streamed` has two destinations, and the cases worth pinning are the ones a description + * cannot draw: a block absent from the ring beside one resident, a step that writes the mirror + * alone (every token of a block's first step), a negative slot, and the state faults libref + * refuses before its first write. Both libraries are compared over both planes -- the ring and the + * mirror -- and `k` / `v` are the engine's rank-2 column slices over a row stride twice the view's + * width, so a store that derives its pitch from the shape writes the previous token's rows. + */ +namespace kvstream { + +Hand store(const char* name, int64_t blocks, int64_t slots, int64_t bs, int64_t kvh, int64_t hd, + std::vector sm, std::vector res) { + const int64_t M = (int64_t)sm.size(); + const int64_t lane = kvh * hd; + const int64_t row = kvh * bs * 2 * hd; + const int64_t span = M * 2 * lane; + Hand h(name, "kv_store_streamed", 0.0); + h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [](int64_t i) { return (float)((int)(i % 31) - 15) * 0.5f; }) /* k */ + .view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [](int64_t i) { return (float)((int)(i % 13) - 6) * 0.25f; }) /* v */ + .idx(sm) + .dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd }, + [](int64_t i) { return (float)((int)(i % 5) + 1); }, true) /* the ring */ + .idx(res) + .dense(RAD_U8, { blocks, row }, + [](int64_t i) { return (float)(int)((i * 37) % 251); }, true) /* the mirror */ + .pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs) + .ps("kv_dtype", "fp8_e4m3"); + return h; +} + +} /* namespace kvstream */ + +void kvstream_cases(std::vector& hs) { + using namespace kvstream; + /* Block 0 absent, block 1 resident in slot 0, block 2 absent, block 3 resident in slot 1. */ + { + Hand h = store("the mirror always, the resident slot too", 4, 2, 2, 2, 4, + { 1, 3, 6, 2 }, { -1, 0, -1, 1 }); + hs.push_back(std::move(h)); + } + /* Nothing resident: the ring must come out untouched and the mirror must hold every row. */ + { + Hand h = store("a cold ring takes the mirror alone", 4, 2, 2, 2, 4, + { 0, 5, 6, 7 }, { -1, -1, -1, -1 }); + hs.push_back(std::move(h)); + } + /* A negative slot is a padded row: neither plane is written. */ + { + Hand h = store("a negative slot stores nothing", 2, 1, 2, 1, 2, { -1, 3 }, { -1, 0 }); + hs.push_back(std::move(h)); + } + /* The parity configuration's identity map: the ring slot is the block, so the two planes hold + * the same bytes at every mapped position. */ + { + Hand h = store("an identity map writes both planes alike", 3, 3, 2, 1, 2, + { 0, 3, 5 }, { 0, 1, 2 }); + hs.push_back(std::move(h)); + } + /* The mirror's exact bytes, laid out by hand: four tokens fill both blocks at both offsets + * with constants, so the paged layout [kv_heads][block_size][2 * head_dim] and the E4M3 + * encoding are pinned against an answer no library computes. Agreement alone cannot catch a + * store that writes the right values at the wrong address or with the wrong scale. */ + { + const int64_t blocks = 2, slots = 2, bs = 2, kvh = 1, hd = 2, M = 4; + const int64_t lane = kvh * hd, row = kvh * bs * 2 * hd, span = M * 2 * lane; + const float kd[M][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; + const float vd[M][2] = { { -1, -2 }, { -3, -4 }, { -5, -6 }, { -7, -8 } }; + Hand h("the mirror's bytes, block-id addressing and E4M3", "kv_store_streamed", 0.0); + h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [&](int64_t i) { return i % 4 < 2 ? kd[i / 4][i % 4] : 0.0f; }) + .view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [&](int64_t i) { return i % 4 < 2 ? vd[i / 4][i % 4] : 0.0f; }) + .idx({ 0, 1, 2, 3 }) + .dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd }, [](int64_t) { return 0.0f; }, true) + .idx({ 0, 1 }) + .dense(RAD_U8, { blocks, row }, [](int64_t) { return 0.0f; }, true) /* the mirror */ + .pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs) + .ps("kv_dtype", "fp8_e4m3"); + std::vector want((size_t)(blocks * row), 0); + for (int64_t t = 0; t < M; ++t) { + const float pair[2 * hd] = { kd[t][0], kd[t][1], vd[t][0], vd[t][1] }; + uint8_t enc[2 * hd] = {}; + h_narrow(pair, RAD_F8E4M3, 2 * hd, enc); + const int64_t blk = t / bs, off = t % bs; + for (int64_t j = 0; j < 2 * hd; ++j) + want[(size_t)(blk * row + off * 2 * hd + j)] = enc[j]; + } + h.expect_bytes(5, want); + hs.push_back(std::move(h)); + } + /* The default cache dtype: both planes hold the values themselves, two bytes an element. */ + { + const int64_t blocks = 4, slots = 2, bs = 2, kvh = 2, hd = 4, M = 4; + const int64_t lane = kvh * hd, row = kvh * bs * 2 * hd * 2, span = M * 2 * lane; + Hand h("bf16: the mirror always, the resident slot too", "kv_store_streamed", 0.0); + h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [](int64_t i) { return (float)((int)(i % 31) - 15) * 0.5f; }) + .view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span, + [](int64_t i) { return (float)((int)(i % 13) - 6) * 0.25f; }) + .idx({ 1, 3, 6, 2 }) + .dense(RAD_BF16, { slots, kvh, bs, 2 * hd }, + [](int64_t i) { return (float)((int)(i % 5) + 1); }, true) + .idx({ -1, 0, -1, 1 }) + .dense(RAD_U8, { blocks, row }, + [](int64_t i) { return (float)(int)((i * 37) % 251); }, true) + .pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs) + .ps("kv_dtype", "bf16"); + hs.push_back(std::move(h)); + } + /* ---- the refusals, before any write ---- */ + { + Hand h = store("a map entry past the ring is refused", 2, 1, 2, 1, 2, { 0, 1 }, { 1, 0 }); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + { + Hand h = store("a claim in flight is a state fault", 2, 1, 2, 1, 2, { 0, 1 }, { -2, 0 }); + h.refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + { + Hand h = store("a slot past the mirror is refused", 2, 1, 2, 1, 2, { 4, 1 }, { -1, 0 }); + h.refuses(RAD_E_SHAPE); + hs.push_back(std::move(h)); + } + /* A mirror row that is not the block's pitch: a write would spill into the next block. */ + { + const int64_t blocks = 2, slots = 1, bs = 2, kvh = 1, hd = 2, row = 8; + Hand h("a padded mirror row is refused", "kv_store_streamed", 0.0); + h.view(RAD_BF16, { 2, 2 }, { 4, 1 }, 8, + [](int64_t i) { return (float)((int)(i % 7) - 3); }) + .view(RAD_BF16, { 2, 2 }, { 4, 1 }, 8, + [](int64_t i) { return (float)((int)(i % 5) - 2); }) + .idx({ 0, 1 }) + .dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd }, [](int64_t) { return 1.0f; }, true) + .idx({ -1, -1 }) + .view(RAD_U8, { blocks, row }, { row + 4, 1 }, blocks * (row + 4), + [](int64_t i) { return (float)(int)(i % 251); }, true) + .pi("M", 2).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs) + .ps("kv_dtype", "fp8_e4m3") + .refuses(RAD_E_STRIDE); + hs.push_back(std::move(h)); + } +} + /* ================================================================== weights of several planes * * A weight declared over several planes of one stored tensor reaches a host row joined @@ -4333,6 +4808,8 @@ bool hand_cases(const Check& ck) { upscaler_cases(hs); vsa_cases(hs); qsa_cases(hs); + kv_cases(hs); + kvstream_cases(hs); encoder_cases(hs); audio_cases(hs); Broken broken; diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index becab33c..a2f88f41 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -100,7 +100,7 @@ int avx_par_force(int threads); X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \ X(lora_shrink) X(lora_expand) X(lora_expand_mm) \ /* ---- attention */ \ - X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \ + X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(kv_store_streamed) X(kv_resolve) X(rope) \ X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \ X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \ X(sam_attn) \ diff --git a/libavx/avx_kvstream.cpp b/libavx/avx_kvstream.cpp new file mode 100644 index 00000000..7533dd35 --- /dev/null +++ b/libavx/avx_kvstream.cpp @@ -0,0 +1,403 @@ +/* avx_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and + * the ring slots its pool holds (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4). + * + * libref/ref_kvstream.cpp is the contract, and this file follows it line by line: the same + * refusals in the same order, the same epoch, the same ascending miss order, the same victim from + * the same CLOCK sweep over the same two-bit heat counter, so the same blocks land in the + * same slots. That is the part a residency + * map cannot get "close" on: `sel` becomes the attention's addressing, and two implementations + * that agreed on residency but disagreed on a victim would read different KV for the same query. + * + * Why its own file rather than a section of avx_qsa.cpp: the op sits beside `qsa_select` in + * docs/OPS.md but is not part of the indexer -- it walks no scores and rotates nothing, it moves + * bytes and owns state across calls (epoch, hand, heat counters). libref keeps the same split + * (ref_qsa.cpp / ref_kvstream.cpp), so the two libraries' files diff against each other. + * + * ============================== what is and is not vector work ============================== + * + * The phases that can run wide do: the rewrite of a `sel` row (a gather of `res[b]` with the + * negative results left in place) and the block copy (one block is a whole number of 16-byte lanes + * at every cache layout, docs/OPS.md). The passes that cannot are the lookup/claim pass, the claim + * gather and the CLOCK sweep, and none of them is a missed opportunity: + * + * the map is its own set (phase 2). Two lanes of one vector naming the same absent block would + * both read -1 and both claim it, which is exactly the double claim -2 exists to prevent, and + * two lanes naming the same resident slot would race on its epoch. The pass is one load and one + * store per entry and is bounded by the selection, not by the cache. The claim gather and the + * revert are the same pass twice more (`lookups` entries each) for the same reason: the list is a + * fact about the selection, and the whole point of this form is that `blocks` -- the id space -- + * never enters a launch's cost. + * + * the sweep is a serial second-chance walk with a moving hand whose result is the placement + * itself. Its cost is one pass over the slots per miss, and a miss is a cold block: the copies + * dominate. + * + * No OpenMP anywhere: the op carries state from call to call (ctl's epoch, hand and counters), so + * two of its launches must never overlap and one launch is a single serial unit of work. This is + * why its row is absent from libr4d's concurrent prefix table; libavx's rows make no concurrency + * promise at all. + * + * Scratch is the arena the other kernels use (avx_common.h), not RadArgs::scratch: the miss list + * and the claim list are per-call temporaries, and the arena is already the plugin's answer for + * one. The layout is `int32 miss_block[slots]`, `int32 miss_slot[slots]` -- what a device row + * declares through RadKernelInfo::scratch -- followed by `int32 claim[lookups]`, the gathered claim + * set this file needs only because it has no workgroup to sort in. + */ +#include "avx_common.h" +#include "avx_vec.h" + +#include + +using namespace avx; + +namespace { + +/* The heat counter's two writes, the same function in all three implementations (libref's + * heat_up/heat_down): a use bumps by one and saturates at 3, a sweep pass halves, and a negative + * value -- never written by a legal call -- reads as cold. */ +int32_t kv_heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); } +int32_t kv_heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; } + +/* `ctl`'s size and the index of its first u64 counter (three consecutive u64s from [4]). */ +enum { kKvCtlInts = 16, kKvCtlMisses = 4, kKvCtlLookups = 6, kKvCtlCalls = 8 }; +static_assert(kKvCtlLookups == kKvCtlMisses + 2 && kKvCtlCalls == kKvCtlMisses + 4, + "the three counters are consecutive u64s from ctl[4]"); + +/* The byte pitch of a rank-2-or-deeper operand's rows, and whether its trailing extents fill that + * pitch densely (libref's row_bytes). Both planes are one block a row: a padded row would copy a + * block's bytes over its neighbour's. */ +int64_t kv_row_bytes(const RadTensor* t, int64_t* dense) { + int64_t acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) acc *= t->shape[i]; + *dense = acc; + return t->stride[0] * rad_dtype_bytes(t->dtype, 1); +} + +/* `block_bytes` of the mirror into a slot of the pool. A copy is a byte copy at every cache + * layout (the op never reads an element), so the width is the ISA's, not the block's dtype. */ +void kv_copy_block(uint8_t* dst, const uint8_t* src, int64_t n) { + int64_t i = 0; +#if AVX_LEVEL >= 3 + for (; i + 64 <= n; i += 64) + _mm512_storeu_si512((void*)(dst + i), _mm512_loadu_si512((const void*)(src + i))); +#elif AVX_LEVEL >= 2 + for (; i + 32 <= n; i += 32) + _mm256_storeu_si256((__m256i*)(dst + i), + _mm256_loadu_si256((const __m256i*)(src + i))); +#elif AVX_LEVEL >= 1 + for (; i + 16 <= n; i += 16) + _mm_storeu_si128((__m128i*)(dst + i), _mm_loadu_si128((const __m128i*)(src + i))); +#endif + if (i < n) std::memcpy(dst + i, src + i, (size_t)(n - i)); +} + +/* The claim list: every distinct block the selection claims, in block-id order. A claim exists only + * where an entry names a block -- the lookup pass left it `-2` -- so the list is gathered from the + * SELECTION, whose length is `lookups = sum_q nsel[q]`: a property of the call. It is deliberately + * not a walk of `res` over `blocks`, which is the group's whole id space and says nothing about how + * big one launch is. The map stays the dedup set: the first entry naming a claim marks it `-3`, so a + * block several rows name enters the list once, and the marks are restored before the sweep sees the + * map. + * + * The caller sorts the list; `cap` is the buffer's length and is `lookups` at least, because a + * distinct claim costs at least one entry, so every claim is written. The contract needs the first + * `slots` of that ascending order and nothing past them. */ +int64_t kv_claims(int32_t* res, int32_t* out, int64_t cap, + const int32_t* sel, const int32_t* nsel, int64_t M, int64_t pitch) { + int64_t n = 0; + for (int64_t q = 0; q < M; ++q) { + const int32_t* const row = sel + q * pitch; + for (int64_t i = 0; i < nsel[q]; ++i) { + const int32_t b = row[i]; + if (res[b] != -2) continue; /* a hit, or taken by an earlier entry */ + res[b] = -3; + if (n < cap) out[n++] = b; + } + } + for (int64_t k = 0; k < n; ++k) res[out[k]] = -2; + return n; +} + +/* Every claim the sweep could not place goes back to -1: the block is not resident, and the next + * call may claim it again. A `res` entry still -2 here is by definition such a claim (a placed one + * holds its slot), and it is named by at least one selection entry, so one pass over the selection + * reaches all of them -- `lookups` entries instead of `blocks` map entries. The write is idempotent, + * so entries that repeat a block are harmless. */ +void kv_relax_claims(int32_t* res, const int32_t* sel, const int32_t* nsel, int64_t M, + int64_t pitch) { + for (int64_t q = 0; q < M; ++q) { + const int32_t* const row = sel + q * pitch; + for (int64_t i = 0; i < nsel[q]; ++i) + if (res[row[i]] == -2) res[row[i]] = -1; + } +} + +/* The rewrite: entry i becomes the slot holding its block, and an entry whose block could not be + * placed becomes slot 0 -- a defined address inside the ring, because leaving the block id would + * make the attention dereference past it. ctl[3] is what marks the table unusable ("Overflow" in + * docs/OPS.md). + * + * The gather is safe by construction: the validation pass refused any entry outside [0, blocks) + * before a byte was written. An entry at or past nsel[q] is never passed in, so `qsa_select`'s -1 + * padding survives. */ +void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) { + int64_t i = 0; +#if AVX_LEVEL >= 3 + const __m512i zero = _mm512_setzero_si512(); + for (; i + 16 <= n; i += 16) { + const __m512i b = _mm512_loadu_si512((const void*)(row + i)); + const __m512i s = _mm512_mask_i32gather_epi32(zero, (__mmask16)0xFFFF, b, + (const void*)res, 4); + /* A gather that lands on a negative is a block this call could not place (-1) or one it + * just claimed (-2): slot 0, not the id, exactly as the scalar tail writes it. Clamping + * says that for the whole vector; masking the store instead would leave the id in place. */ + _mm512_storeu_si512((void*)(row + i), _mm512_max_epi32(s, zero)); + } +#elif AVX_LEVEL >= 2 + const __m256i all = _mm256_set1_epi32(-1); + const __m256i zero = _mm256_setzero_si256(); + for (; i + 8 <= n; i += 8) { + const __m256i b = _mm256_loadu_si256((const __m256i*)(row + i)); + const __m256i s = _mm256_mask_i32gather_epi32(zero, res, b, all, 4); + /* s > -1 is s >= 0; a negative lane becomes 0 ("Overflow"), never the block id it holds. */ + const __m256i ok = _mm256_cmpgt_epi32(s, all); + _mm256_storeu_si256((__m256i*)(row + i), _mm256_blendv_epi8(zero, s, ok)); + } +#endif + for (; i < n; ++i) { + const int32_t s = res[row[i]]; + row[i] = s >= 0 ? s : 0; + } +} + +} /* namespace */ + +/* ------------------------------------------------------------------ kv_resolve */ +/* One call: bump the epoch; one lookup per distinct block (a hit stamps the slot with the epoch and + * bumps its heat counter, an absent block becomes a claim and joins the miss list once); place one + * victim per miss -- the block's own slot when its id fits the ring and that slot is free (a + * context shorter than the ring maps block id to slot), otherwise a free slot first, then CLOCK from + * the hand over the two-bit heat counter, which never takes a slot this call has stamped; re-point + * both maps; copy each missed block from the mirror; rewrite every valid entry. `nsel` and the + * attention's length are untouched: + * a selection entry is an address, not a count. + * + * `kv_cache` is the RAD_KV operand the attention and `kv_store` take, and it is INOUT rather than + * OUT: only the slots a miss lands in are written and every other slot of the ring must survive + * for the blocks still resident there. + * + * An entry of a miss the sweep could not place is rewritten to slot 0, not left holding its block + * id: on device the id is an address past the ring that `attn_paged` dereferences unchecked, and a + * measured overflow must produce wrong numbers the caller discards (ctl[3]), not a fault. */ +AVX_KERNEL(kv_resolve) { + if (!rad_args_have(a, 8)) return RAD_E_INVAL; + const RadTensor *sel = &a->t[0], *nsel = &a->t[1], *res = &a->t[2], *sblk = &a->t[3]; + const RadTensor *sst = &a->t[4], *ctl = &a->t[5], *host = &a->t[6], *pool = &a->t[7]; + const int64_t M = p_int(a, "M", 0), blocks = p_int(a, "blocks", 0); + const int64_t slots_decl = p_int(a, "slots", 0), pitch = p_int(a, "sel_pitch", 0); + const int64_t bbytes = p_int(a, "block_bytes", 0); + /* Zero rows is not a call (docs/OPS.md). */ + if (M <= 0) return RAD_E_SHAPE; + if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE; + + /* The map and the counts are one format, written by one op and read by the writer and the + * sweep: i32, dense. */ + const RadTensor* const state[] = { sel, nsel, res, sblk, sst, ctl }; + for (const RadTensor* t : state) + if (t->dtype != RAD_I32) return RAD_E_DTYPE; + if (sel->rank != 2 || sst->rank != 2) return RAD_E_SHAPE; + if (sel->shape[0] < M || sel->shape[1] < pitch) return RAD_E_SHAPE; + if (sel->stride[1] != 1 || sel->stride[0] != pitch) return RAD_E_STRIDE; + if (numel(nsel) < M || nsel->stride[0] != 1) return RAD_E_SHAPE; + if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE; + /* The operand states the ring and the parameter is its declared ceiling, as `sel` states `M` + * (libref/ref_kvstream.cpp, "The parameters"): the pool is planned after declare, so a ring the + * engine sized smaller (--kv-resident) arrives as a shorter `slot_block`. */ + const int64_t slots = numel(sblk); + if (slots < 1 || slots > slots_decl || sblk->stride[0] != 1) return RAD_E_SHAPE; + if (sst->shape[0] < slots || sst->stride[1] != 1 || sst->stride[0] < 2) return RAD_E_STRIDE; + if (numel(ctl) < kKvCtlInts || ctl->stride[0] != 1) return RAD_E_SHAPE; + if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE; + if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE; + + /* One block of one layer: the mirror's row and the pool's slot are the same bytes, and + * `block_bytes` is both pitches -- the length of every copy. */ + int64_t hdense = 0, pdense = 0; + if (kv_row_bytes(host, &hdense) != bbytes || + hdense * rad_dtype_bytes(host->dtype, 1) != bbytes) + return RAD_E_STRIDE; + if (kv_row_bytes(pool, &pdense) != bbytes || + pdense * rad_dtype_bytes(pool->dtype, 1) != bbytes) + return RAD_E_STRIDE; + + int32_t* const R = (int32_t*)res->data; + int32_t* const SB = (int32_t*)sblk->data; + int32_t* const ST = (int32_t*)sst->data; + int32_t* const C = (int32_t*)ctl->data; + const int32_t* const NS = (const int32_t*)nsel->data; + int32_t* const SE = (int32_t*)sel->data; + const int64_t stp = sst->stride[0]; + /* The counters are read and written as u64 inside an i32 block. */ + if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE; + + /* ---- everything that can refuse, before anything is written; the entry count is summed here + * so the counter and the claim list's length need no second look at `nsel` ---- */ + int64_t lookups = 0; + for (int64_t q = 0; q < M; ++q) { + const int64_t n = NS[q]; + if (n < 0 || n > pitch) return RAD_E_SHAPE; + const int32_t* const row = SE + q * pitch; + for (int64_t i = 0; i < n; ++i) + if (row[i] < 0 || row[i] >= blocks) return RAD_E_INVAL; + lookups += n; + } + /* The map's own domain, over the whole of it. This is a state fault the contract refuses + * (`-2` is never left by a call; a slot index outside the ring would address past it), not a + * fallback: an entry the map holds and no selection entry names can only be found by looking + * at the map, so this pass is `blocks` long in the reference and here alike. Everything that + * acts on a claim is bounded by the selection, as above. */ + for (int64_t b = 0; b < blocks; ++b) + if (R[b] < -1 || R[b] >= slots) return RAD_E_INVAL; /* -2 is never left by a call */ + for (int64_t s = 0; s < slots; ++s) + if (SB[s] < -1 || SB[s] >= blocks) return RAD_E_INVAL; + if (C[1] < 0 || C[1] >= slots) return RAD_E_INVAL; + + /* ---- 1. the epoch ---- */ + const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u); + + /* ---- 2. hits, and one claim per distinct miss (the map is its own set) ---- */ + for (int64_t q = 0; q < M; ++q) { + const int64_t n = NS[q]; + const int32_t* const row = SE + q * pitch; + for (int64_t i = 0; i < n; ++i) { + const int32_t b = row[i]; + const int32_t s = R[b]; + if (s >= 0) { + /* The epoch stamps the slot; the heat counter gains one step, once a slot a call + * (libref's step 2), so the counter measures calls that wanted the block. */ + if (ST[s * stp] != epoch) { + ST[s * stp] = epoch; + ST[s * stp + 1] = kv_heat_up(ST[s * stp + 1]); + } + } else if (s == -1) { + R[b] = -2; + } + } + } + + /* ---- 3. the canonical miss order ---- */ + int32_t* const miss_block = (int32_t*)scratch_raw((size_t)(2 * slots + lookups) * sizeof(int32_t)); + int32_t* const miss_slot = miss_block + slots; + int32_t* const claim = miss_slot + slots; + const int64_t nclaims = kv_claims(R, claim, lookups, SE, NS, M, pitch); + std::sort(claim, claim + nclaims); + const int64_t nmiss = nclaims < slots ? nclaims : slots; + for (int64_t k = 0; k < nmiss; ++k) miss_block[k] = claim[k]; + + /* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot + * this call uses ---- */ + /* Identity first: a block whose id fits the ring and whose own slot is free goes there, so a + * context shorter than the ring gets res[b] = b and the attention's run of adjacent ids reads + * adjacent slots of one layer's stripe (libref's step 4; +2.07% at 16k, §26). It takes only a + * free slot and does not move the hand, so it never evicts and the fallback below is the old + * policy exactly, from the hand it would always have seen. + * + * Free before live: the ring's empty region fills before any resident block is evicted (see + * libref's step 4). The free scan has no side effect when it finds nothing, so a full ring + * takes the same CLOCK victim it always took. The count is what keeps a full ring from paying + * that scan per miss: a placement makes a free slot live and an eviction re-points a live one, + * so a zero count holds for the rest of the call. */ + int64_t free_left = 0; + for (int64_t s = 0; s < slots; ++s) + if (SB[s] < 0 && ST[s * stp] != epoch) ++free_left; + int64_t hand = C[1]; + int64_t placed = 0; + /* More claims than the ring can hold means some miss was left unplaced by construction -- the + * list here is the first `slots` of the claim set, so the sweep cannot discover it by running + * out of misses -- and libref latches exactly that. */ + bool overflow = nclaims > slots; + for (int64_t k = 0; k < nmiss; ++k) { + const int32_t b = miss_block[k]; + int64_t victim = -1; + if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b)) + victim = b; + if (victim < 0 && free_left > 0) { + int64_t h = hand; + for (int64_t scanned = 0; scanned < slots; ++scanned) { + const int64_t s = h; + h = h + 1 == slots ? 0 : h + 1; + if (ST[s * stp] == epoch) continue; /* used by this call */ + if (SB[s] >= 0) continue; /* holds a block */ + victim = s; + hand = h; + break; + } + if (victim < 0) free_left = 0; + } + if (victim < 0) { + for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) { + const int64_t s = hand; + hand = hand + 1 == slots ? 0 : hand + 1; + if (ST[s * stp] == epoch) continue; /* used by this call */ + if (SB[s] >= 0 && ST[s * stp + 1] > 0) { /* second chance */ + ST[s * stp + 1] = kv_heat_down(ST[s * stp + 1]); + continue; + } + victim = s; + break; + } + } + if (victim < 0) { + /* Every slot of the ring is stamped with this call's epoch: nothing left to take, and + * taking a slot this call filled would break the table it is about to hand out. */ + overflow = true; + break; + } + /* ---- 5. re-point both maps ---- */ + if (SB[victim] < 0 && free_left > 0) --free_left; /* a free slot just filled */ + if (SB[victim] >= 0) R[SB[victim]] = -1; + SB[victim] = b; + ST[victim * stp] = epoch; + ST[victim * stp + 1] = kv_heat_up(ST[victim * stp + 1]); + R[b] = (int32_t)victim; + miss_slot[k] = (int32_t)victim; + ++placed; + } + kv_relax_claims(R, SE, NS, M, pitch); + + /* ---- 6. the copies, one block each, in miss order ---- */ + const uint8_t* const hb = (const uint8_t*)host->data; + uint8_t* const pb = (uint8_t*)pool->data; + for (int64_t k = 0; k < placed; ++k) + kv_copy_block(pb + (int64_t)miss_slot[k] * bbytes, + hb + (int64_t)miss_block[k] * bbytes, bbytes); + + /* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */ + for (int64_t q = 0; q < M; ++q) kv_rewrite_row(SE + q * pitch, NS[q], R); + + /* ---- the bookkeeping ---- */ + /* Distinct blocks, counted from the slots this call stamped: a hit or a placed miss leaves the + * call's epoch in its slot, and the misses it could not place are the rest of the union. Entry + * counts would overcount, because many of a launch's rows share swaths of the history. */ + int64_t used = 0; + for (int64_t s = 0; s < slots; ++s) + if (ST[s * stp] == epoch) ++used; + /* The union is over DISTINCT blocks, so it is the slots this call stamped plus the claims it + * could not place -- exactly libref's count, and now that the whole claim set is known rather + * than a list clipped at `slots`, an overflow reports the union it selected too. */ + const int64_t uni = used + nclaims - placed; + C[0] = epoch; + C[1] = (int32_t)hand; + C[2] = (int32_t)placed; + if (overflow) C[3] = 1; + /* The measured sizes: this call's selection union, the part of it that had to be copied in, and + * the depth of its claim list. */ + if (uni > C[10]) C[10] = (int32_t)uni; + if (placed > C[11]) C[11] = (int32_t)placed; + if (nclaims > C[12]) C[12] = (int32_t)nclaims; + uint64_t* const ctr = (uint64_t*)(C + kKvCtlMisses); + ctr[0] += (uint64_t)placed; + ctr[1] += (uint64_t)lookups; + ctr[2] += 1u; + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index aaaf5884..174246fc 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -324,6 +324,28 @@ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT( P_F64O("k_scale"), P_F64O("v_scale") }; static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping"), INOUT("kv_cache") }; +/* The streamed store: kv_store's parameters and the group's two copies beside the ring. `host` is + * the authoritative mirror and is always written; `res` is the residency map and is read only. */ +static const RadParamSpec pKvStoreStreamed[] = { + P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"), + P_F64O("k_scale"), P_F64O("v_scale") +}; +static const RadOperandSpec oKvStoreStreamed[] = { OPD("k"), OPD("v"), OPD("slot_mapping"), + INOUT("kv_cache"), OPD("res"), + INOUT("host") }; + +/* The residency map of a streamed group. Every operand is i32 state or a byte plane, so no dtype + * parameter: the op is the same code at every cache layout. `kv_cache` is the same RAD_KV operand + * (docs/OPS.md, `kv_resolve`) the attention and kv_store take, INOUT for the same reason kv_store's + * is -- only the slots a miss lands in are written. No constraint either: `block_size` is + * deliberately not a parameter here, because `Builder::find_kv_consumer` binds a KV group to the + * first unclaimed op after it carrying `block_size`, and that must stay the resolved attention + * kernel, not the op that only copies its pages. */ +static const RadParamSpec pKvResolve[] = { P_INT("M"), P_INT("blocks"), P_INT("slots"), + P_INT("sel_pitch"), P_INT("block_bytes") }; +static const RadOperandSpec oKvResolve[] = { INOUT("sel"), OPD("nsel"), INOUT("res"), + INOUT("slot_block"), INOUT("slot_state"), + INOUT("ctl"), OPD("host"), INOUT("kv_cache") }; static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), @@ -1026,6 +1048,20 @@ static const RadOpSchema kSchemas[] = { "each tile to all of its rows. logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w] over the head's " "whole head_dim, softmax in f32 with the max subtracted, out = sum p*v, pad rows dropped." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." }, +{ "kv_store_streamed", ARR(pKvStoreStreamed), ARR(oKvStoreStreamed), + "kv_store for a streamed group: writes k and v into the host mirror always, at the block's " + "identity row, and into the ring slot only when the residency map says the block is resident. A " + "negative slot is skipped; the mirror is the truth and a block absent from the ring is copied in " + "whole by kv_resolve." }, +{ "kv_resolve", ARR(pKvResolve), ARR(oKvResolve), + "Makes every block the selections name resident and rewrites them as ring slots: an epoch bump, " + "a hit or a single claim per distinct block, a free slot before any resident one and otherwise " + "one CLOCK (second-chance) victim per miss - never a slot this call uses - the two maps " + "re-pointed, each missed block copied from the host mirror " + "into its slot, then every valid sel entry replaced by the slot holding its block. nsel, and so " + "the attention's length, are unchanged. The ring must hold the call's distinct blocks; a call " + "that cannot place every miss latches ctl[3] and leaves those entries naming blocks, never a " + "fabricated slot." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." }, { "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey), "QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with " @@ -1601,6 +1637,12 @@ SIMPLE("avx_sam_attn", "sam_attn", "attn", L(sam_attn)), ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)), +ROW("avx_kv_store_streamed", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the resident ring slot", DT_ANY, + cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store_streamed)), +SIMPLE("avx_kv_resolve", "kv_resolve", "attn", + "streamed KV residency map: selected block ids become ring slots, misses copied in", + "i32 maps, u8 block planes", L(kv_resolve)), SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)), SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT, L(rope_table)), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 96ed0e97..f9d305af 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -160,6 +160,7 @@ set(R4D_UNITS "r4d_qsa_block_key_bf16|" "r4d_qsa_score_bf16|" "r4d_qsa_select_bf16|" + "r4d_kv_resolve|" "r4d_qsa_tail_store_bf16|" "r4d_qsa_work_bf16|" "r4d_sample_chain_f32|" diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index dfa95d2a..447d76b6 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -586,6 +586,43 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u } } +/* ========================================================================================== + * qk_norm_rope_gate_kv_store_streamed -- the same prologue with the STREAMED store folded on. + * (row: qk_norm_rope_gate_kv_store_streamed_fp8; kernel: r4d_qk_norm_rope_gate.hip under + * QK_KV_STREAMED) + * + * Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out? + * [7] k_out [8] gate_out? [9] v [10] slot_mapping [11] kv_cache + * [12] res [13] host + * + * The store is `kv_store_streamed`, whose `k` is the prologue's own `k_out`. */ +extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p, + uint64_t present, int step, + RadFuseStep* out) { + if (!out) return RAD_E_INVAL; + auto opt = [present](int i) { return opt_opd(present, i); }; + switch (step) { + case 0: { + Step s(out, "qk_norm_rope_gate"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head") + .mirror(p, n_p, "n_head_kv").mirror(p, n_p, "rot").mirror(p, n_p, "q_dtype") + .mirror_opt(p, n_p, "eps").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "cs_f32") + .mirror_opt(p, n_p, "pos_i64"); + return s.wire({ opt(0), 1, 2, 3, opt(4), 5, opt(6), 7, opt(8) }); + } + case 1: { + Step s(out, "kv_store_streamed"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv") + .mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype") + .mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale"); + /* k_out, v, slot_mapping, kv_cache, res, host */ + return s.wire({ 7, 9, 10, 11, 12, 13 }); + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v. * (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libr4d/r4d_qkv_norm_rope.hip, diff --git a/libr4d/r4d_kv_resolve.hip b/libr4d/r4d_kv_resolve.hip new file mode 100644 index 00000000..b741ba54 --- /dev/null +++ b/libr4d/r4d_kv_resolve.hip @@ -0,0 +1,814 @@ +// kv_resolve: turn a streamed KV group's selected block ids into the ring slots that hold them, +// copy a block in from the pinned host mirror when it is not resident, and rewrite the selection +// in place (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4 and §4.2). +// +// `qsa_select` already writes the group's pool page id into `sel`, and `attn_paged` reads every +// entry as a raw pool index. A streamed group's device pool is `slots` blocks deep while the id +// space is `blocks`, so an id is no longer an address; after this op each entry is a slot of +// `kv_cache` and the attention is unchanged. `sel` is the only place the sparse path names KV +// storage, which is why one op between select and attention suffices. +// +// The order is the contract (libref/ref_kvstream.cpp), because two implementations must place the +// same blocks in the same slots and so produce the same table: +// +// 1. bump the epoch (ctl[0] + 1); +// 2. one lookup per entry below nsel[q]: a hit takes the epoch and, the first time this call +// stamps that slot, bumps its two-bit heat counter by one (clamped at 3) -- one bump a slot a +// call, not one an entry, so a block many rows name gains one step of heat, the same as one a +// single row names. A miss claims its map entry once (-1 -> -2, atomicCAS), so the map is its +// own set. That CAS is also the distinct-claim count: it succeeds exactly once per block, +// which is the +// `s_distinct` step 3 would otherwise have to scan the map for. The value read is kept, one +// int an entry, for step 7 below; +// 3. compact the claimed blocks out of `res` in ASCENDING block id. The claims are made by +// whichever thread reaches them first, but this scan is what fixes the miss order, so +// atomic claim order never reaches the placement. A thread owns one contiguous chunk of the +// map and reads it four ids at a time, so the list is still ascending by construction. Only +// taken when the call claimed something: with no claim there is no `-2` and nothing to +// place (step 2's count says so); +// 4. one victim per miss, in the hand order from ctl[1]: a FREE slot (slot_block < 0) first, so +// no resident block is evicted while the ring has room (the free count is taken in parallel +// once per call); only a call with no free slot falls back to CLOCK's second chance, where a +// slot stamped with this call's epoch is passed and keeps its counter, a warm slot (counter +// non-zero) has its counter HALVED and is passed, and a cold slot (counter 0) is taken. The +// hand PICKS the victim: this is a per-visit decision, so the policy costs no reduction, no +// barrier and no extra traffic -- an add-and-clamp and a shift where a constant store and a +// zero store would do. An exact LRU would need the minimum over the ring per miss, a +// collective reduction that pays more than the choice is worth. The hand ends just past the +// last slot taken; the sweep visits at most 3*slots, because every write clamps the counter +// to 3 and two halvings take any value to 0; +// 5. re-point both maps as each victim is taken (`res[old] = -1`, then slot -> b and b -> slot, +// with the slot's counter bumped by one as a use: the victim's is 0 by construction, so it is +// 1 in the common case, and the clamp keeps a slot taken by identity or from the free region +// inside [0, 3]); +// 6. copy `block_bytes` of host[b] into kv_cache[s] for each placed miss, as bytes, in this one +// launch; +// 7. rewrite every entry below nsel[q] whose block is resident as its slot; entries past nsel[q] +// keep qsa_select's -1 padding. An entry step 2 saw resident uses the slot it read there, so +// `res` is read once a selection entry, not twice (see "THE ENTRY CACHE"). +// +// OVERFLOW. The ring must hold the union of the call's selection (`hits + misses <= slots`). When it +// does not, the sweep cannot place every miss: the unplaced claims are reverted to -1 (so a later +// call may claim them again), ctl[3] is latched to 1, and their selection entries are rewritten to +// SLOT 0 rather than left holding the block id. The id would be an address past the ring, which +// attn_paged dereferences with no bounds check, so an overflow would fault or read another layer; +// slot 0 is defined memory, wrong numbers the caller discards on ctl[3]. +// +// STATE. The epoch, the hand, the two-bit heat counters and the counters live between launches, so +// this row is not concurrent (r4d_rows.cpp's kStateful[]): two launches must never overlap, and the +// engine orders them. It is still recordable: the maps, the ring and the mirror are fixed-size +// from the group's declaration, so addresses and pitches never move. +// +// COST. A decode step issues this once per QSA layer -- twelve launches, in a step whose whole +// budget is ~33 ms -- so a launch's own cost is the miss path, not the dispatch: ~20 to ~60 misses +// a launch at 16k-160k of history. Everything that path touches is therefore sized from the call's +// own entries and not from `blocks`: +// +// - the claim list comes out of the lookup pass, which already sees every claim, so no pass walks +// `res` over `blocks`; +// - the union is a metric (`ctl[10]`), counted on the first stamp per slot, so no pass walks +// `slot_state` over `slots`: a ring is sized by misses and not by slots, and a ring larger than +// the history does not cost more than a small one; +// - the copies are independent, so each miss has a warp of its own and every miss's read is in +// flight at once. +// +// What is left is the host read itself: a miss copies 2 KiB from a pinned mirror page the card has +// not touched, so it is PCIe transactions with a page walk behind them, and no arrangement of the +// copy loop changes that. The CLOCK sweep is not the cost either: each launch halves the counters +// of the slots it passes, so the ring arrives at the next launch mostly cold and a sweep visits +// about one slot a miss. The free-slot scan ahead of it costs a visit per slot it passes, and the +// count that says whether to scan at all (phase 3b) is one coalesced pass over the two slot maps per +// call, so a ring with no free slot -- where every eviction is unavoidable -- pays neither a full +// turn of scanning per miss nor one serial scan per launch. +// +// SCRATCH. `next_pow2(slots)` block ids then `slots` slots (the row's scratch hook sizes it). The +// miss list is a per-call temporary and would cost the arena planner, the recorded pass and the +// tape key bytes nothing outside this launch reads. The claim list is dynamic LDS (`cap` ids) while +// it fits -- the sort reads every element from every thread, so it wants shared memory -- and the +// scratch's first plane when it does not, which is why that plane is padded to a power of two. The +// entry cache is dynamic LDS too, after the claim list, and absent when it does not fit. +// +// THE CLAIM LIST'S SIZE IS DERIVED, NOT WRITTEN DOWN. A claim is a distinct absent block the +// selection names, so one call makes at most `M * sel_pitch` of them -- and at most `lookups = +// sum_q nsel[q]` in fact -- which is a fact about the call and not about the cache: `blocks` is the +// id space, `max_seqs * ceil(max_ctx / block_size)` and never the size of a launch. So the +// launcher sizes the list at `next_pow2(min(M * sel_pitch, the room a workgroup has))`, and for +// `--max-num-seqs 4` at `sel_pitch` 513 that is 4096 ids, where a constant would have to be chosen +// for the largest configuration or hand that one the map walk below. Nothing here mentions +// `max_seqs`: the engine declares `sel_pitch` and launches `M` rows, and any --max-num-seqs follows +// from those two. `ctl[12]` records the largest claim count one call has made, so a list that is +// ever too shallow is visible in the counters rather than only in the launch's time. +// +// Only the first `slots` claimed blocks are needed: the sweep cannot place more than `slots`, and +// every claim past that is still reverted to -1 by the final pass, so a capped list changes no +// placement. +// +// ABOVE THE LIST. A launch wider than the list -- 28 or more rows at `sel_pitch` 513, since a +// workgroup has tens of thousands of ids of room -- gathers its claims from the selection into the +// scratch and sorts them there (phase 3). The walk is over the call's entries, `lookups` of them, +// never over `blocks`: the map is only the set that says whether an id is a claim and that keeps a +// block four rows name out of the list four times. Same ids, same ascending order, same placements +// as the fast path. The one call this cannot serve is one claiming more blocks than the ring holds: +// no structure there can hold the whole claim set, so that call -- which has overflowed and whose +// step the caller discards -- keeps the map walk that puts the smallest `slots` claims in order. +// +// THE ENTRY CACHE. Step 2 and step 7 each read `res[b]` for every selection entry, and those reads +// are scattered over `blocks` i32: at decode that is two 513-load waves over a map the launch has +// already touched once. But step 7's answer for a HIT is step 2's +// answer: the only thing that clears a `res` entry in a call is an eviction, and the sweep never +// takes a slot stamped with this call's epoch (the `slot_state` test in both the free scan and the +// CLOCK sweep), which is exactly the stamp step 2 puts on every hit's slot. So a hit's slot cannot move, and only an entry step 2 saw absent can +// change -- a claimed block becomes its placed slot, or stays -1 when the sweep could not place it +// (step 6a's revert), or in the above-the-list path passes through -3 and back. Step 2 therefore +// stores the value it read, one int an entry, and step 7 uses it when it is >= 0 and reads the map +// only otherwise: the same slots, the same `sel`, one scattered wave instead of two. +// +// The cache is `M * sel_pitch` ints of dynamic LDS, the launch's whole entry count, and only while +// the workgroup has that room beside the claim list; a prefill-shaped launch that has not gets +// zero and step 7 reads the map instead. Nothing outside the launch sees it: no operand, +// no scratch, no contract. Entries whose block id is out of range are skipped in both steps and +// never reach the cache, and the read is by `sel`'s entry index, which is the same index -- and the +// same thread -- in both steps, so no barrier is needed between them. +// +// STATE FAULTS. libref refuses a `res` entry outside [-1, slots), a `slot_block` outside +// [-1, blocks), a hand outside [0, slots) and a selection entry outside [0, blocks) before it +// writes anything. A device launch cannot return a host status from inside its kernel, so this +// kernel guards instead: an out-of-range hand starts at 0, a map value outside its domain is not +// used to address memory, an out-of-range block id is left in `sel`, and nsel is clamped to +// `sel_pitch` so a bad count cannot steer a row into its neighbour. Those paths are the state +// fault libref refuses; a legal call never takes them and is bit-identical to the reference. +// +// The shape checks (ranks, dtypes, pitches, byte extent per block) belong to the shim below. Like +// every step-sized kernel it takes the launch's row count and row pitch from `sel`'s own extent, +// not from the ranged `M`/`sel_pitch` parameters: `M` arrives as the band's ceiling, so a one-row +// decode and a 625-token prefill would otherwise be refused (arch/common/rad_arch.h's "step-sized +// operands"). `M` is still checked as the ceiling it is, so a genuinely over-wide launch is refused. +// The ring depth is the operand's for the same reason: `slot_block`'s extent is the ring this call +// may address, and the declared `slots` is the ceiling it may not pass -- the pool is planned after +// declare, so a ring the engine sized smaller (--kv-resident) arrives shorter. +// It reads the two byte planes by row pitch in bytes, as libref does, so the same kernel serves +// every cache layout (`fp8`, `fp8_v4`, `k6_v4`, `bf16`) and the copy converts nothing. +// +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. + +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_launch.h" + +#include +#include + +namespace { + +constexpr int kThreads = 1024; + +/* A 16-byte vector as a builtin type, not `uint4`: the class copies through a memcpy call, and the + * miss copy needs its four loads to stay four loads (phase 6). */ +typedef unsigned int kv_v16 __attribute__((ext_vector_type(4))); + +/* The next power of two at or above `n`, clamped to what an i32 can index: the sort pads to one and + * the row's scratch is sized from the same expression. */ +static long long kv_pow2ceil(long long n) { + long long p = 1; + while (p < n && p <= (1LL << 30)) p <<= 1; + return p; +} + +/* The claim list's capacity, in ids, from the launch's own operands and the device's LDS room (the + * header above, "the claim list's size is derived"). `0` means a workgroup has no room at all, which + * the shim refuses. `*room_out` is the dynamic LDS room in ints, so the entry cache can take what the + * claim list leaves (header, "the entry cache"). */ +static int kv_claim_cap(long long M, long long pitch, int* room_out) { + /* Static LDS: the two reduction arrays and the scalars. Everything else is dynamic. */ + const size_t stat = (size_t)kThreads * 2 * sizeof(int) + 64; + static const int room = [] { + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return 0; + hipDeviceProp_t pr{}; + if (hipGetDeviceProperties(&pr, dev) != hipSuccess) return 0; + if (pr.sharedMemPerBlock <= stat) return 0; + size_t r = (pr.sharedMemPerBlock - stat) / sizeof(int); + size_t p = 1; + while (p * 2 <= r) p *= 2; /* a power of two: the sort pads to one, and must not pad + * past the buffer */ + return (int)p; + }(); + *room_out = room; + if (room < 1) return 0; + /* The largest power of two the room holds: `cap` is always one, because the sort pads the list + * to a power of two and must not pad past the buffer. */ + int top = 1; + while (top <= room / 2) top *= 2; + const long long bound = M * pitch; /* the call's claim ceiling */ + int p = 1; + while ((long long)p < bound && p < top) p <<= 1; + return p; +} + +/* The heat counter's two writes, the same function in all three implementations (libref's + * heat_up/heat_down): a use bumps by one and saturates at 3, a sweep pass halves, and a negative + * value -- never written by a legal call -- reads as cold rather than surviving every pass. */ +__device__ __forceinline__ int kv_heat_up(int h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); } +__device__ __forceinline__ int kv_heat_down(int h) { return h > 0 ? (h >> 1) : 0; } + +/* Ascending order of `n` distinct claim ids in the claim list, padded to a power of two with + * INT32_MAX, which sorts past every block id. A caller's buffer, because both paths sort: the whole + * claim set when it fits the list and one window of the id space when it does not. Block ids are + * distinct, so no equal pair decides anything. */ +__device__ __forceinline__ void kv_sort_claims(int* list, int n, int tid) { + int n2 = 1; + while (n2 < n) n2 <<= 1; + for (int i = n + tid; i < n2; i += kThreads) list[i] = INT32_MAX; + __syncthreads(); + for (int k = 2; k <= n2; k <<= 1) { + for (int j = k >> 1; j > 0; j >>= 1) { + for (int i = tid; i < n2; i += kThreads) { + const int ixj = i ^ j; + if (ixj > i) { + const int a = list[i], b = list[ixj]; + /* Ascending overall: a pair whose lower index sits in the first half of a + * k-block sorts up, the other half sorts down (bitonic). */ + const bool up = (i & k) == 0; + if (up ? a > b : a < b) { list[i] = b; list[ixj] = a; } + } + } + __syncthreads(); + } + } +} + +__global__ __launch_bounds__(kThreads) void kv_resolve_kernel( + int32_t* __restrict__ sel, const int32_t* __restrict__ nsel, + int32_t* __restrict__ res, int32_t* __restrict__ slot_block, + int32_t* __restrict__ slot_state, int32_t* __restrict__ ctl, + const uint8_t* __restrict__ host, uint8_t* __restrict__ cache, + int32_t* __restrict__ miss_block, int32_t* __restrict__ miss_slot, + int M, int blocks, int slots, int pitch, int bbytes, int sst_ld, int cap, int ecache) { + + __shared__ int s_epoch, s_lookups, s_nmiss, s_distinct, s_placed, s_overflow, s_claims, s_hits; + __shared__ int s_free; + __shared__ int s_cnt[kThreads], s_off[kThreads]; + /* The claim list, before the sort, `cap` ids of dynamic LDS (kv_claim_cap). Shared rather than + * the row's scratch because the sort reads every element from every thread; the scratch still + * holds the placed miss list, which is what the row declares and what the sweep and the copies + * walk in order. `ecache` ints follow it: the value this call's lookup read for each selection + * entry, which step 7 reuses (header, "the entry cache"). */ + R4D_DYN_LDS(int, s_dyn); + int* const s_list = s_dyn; + int* const s_ent = s_dyn + cap; + /* The claim gather's fill counter. */ + __shared__ int s_wc; + + const int tid = (int)threadIdx.x; + + /* ---- 1. the epoch ---- */ + if (tid == 0) { + s_epoch = ctl[0] + 1; + s_lookups = 0; + s_claims = 0; + s_hits = 0; + s_distinct = 0; + s_nmiss = 0; + s_placed = 0; + s_overflow = 0; + s_free = 0; + /* This call's miss count. A call that claims nothing returns it as zero below without + * reaching the sweep, so it is cleared here rather than left as the last call's. */ + ctl[2] = 0; + } + __syncthreads(); + const int epoch = s_epoch; + + /* ---- 2. one lookup per entry; the map is its own set ---- */ + int lookups = 0, hits = 0; + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + lookups += n; + for (int i = tid; i < n; i += kThreads) { + const size_t e = (size_t)q * pitch + i; + const int b = sel[e]; + if ((unsigned)b >= (unsigned)blocks) continue; + const int s = res[b]; + /* The value this lookup saw, for step 7: a hit's slot cannot move in this call (the + * sweep passes every slot this pass stamps with the epoch), so only an entry that was + * absent here needs the map read again. Header, "the entry cache". */ + if (ecache > 0) s_ent[e] = s; + if (s >= 0 && s < slots) { + /* The stamp is this call's mark on the slot and the union's counter at once: the + * exchange says whether this thread was the first to stamp it, so the ring is + * counted here instead of walked after the fact. */ + if (atomicExch(&slot_state[(size_t)s * sst_ld], epoch) != epoch) { + /* One bump a slot a call: the exchange says this thread was the first to stamp + * it, so a block twenty rows name gains one step of heat, not twenty. */ + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_up(slot_state[(size_t)s * sst_ld + 1]); + ++hits; + } + } else if (s == -1) { + /* One CAS wins per block, so this is the distinct-claim count, and the claim list + * needs no walk over `res` to find them. */ + if (atomicCAS(&res[b], -1, -2) == -1) { + const int k = atomicAdd(&s_claims, 1); + if (k < cap) s_list[k] = b; + } + } + } + } + /* The launch's hit count: a per-thread total, then the same warp-first reduction the union + * ends with. */ + s_cnt[tid] = hits; + __syncthreads(); + if (tid < 32) { + int t = 0; + for (int i = tid; i < kThreads; i += 32) t += s_cnt[i]; + s_off[tid] = t; + } + __syncthreads(); + if (tid == 0) { + int used = 0; + for (int t = 0; t < 32; ++t) used += s_off[t]; + s_hits = used; + s_lookups = lookups; + s_distinct = s_claims; + } + __syncthreads(); + + /* ---- 3. the canonical miss order: ascending block id ---- */ + const int claims = s_distinct; + const int want = claims < slots ? claims : slots; + if (claims > 0) { + if (claims <= cap) { + /* The list holds every claim, so sorting it says exactly what walking `res` said -- + * ascending block id -- over `claims` elements instead of `blocks`. */ + kv_sort_claims(s_list, claims, tid); + for (int i = tid; i < want; i += kThreads) miss_block[i] = s_list[i]; + } else { + /* Above the list: the launch is wide enough that `M * sel_pitch` -- the claim ceiling + * it declares -- passes the workgroup's LDS room, so the list is not held in shared + * memory. The claims are gathered from the selection into the row's scratch instead and + * sorted there, over `lookups` entries: the same ids, the same ascending order, and + * still nothing about `blocks` in the cost. Only a call that fits its ring takes this + * path; a call with more claims than the ring has slots cannot be listed at all and + * keeps the map walk below, because a sorted list of the smallest `slots` claims has to + * come from the whole claim set. */ + if (claims <= slots) { + if (tid == 0) s_wc = 0; + __syncthreads(); + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + /* One claim per distinct block: the map is the set, so a block four rows + * name enters the list once. -3 is "collected", restored below. */ + if (atomicCAS(&res[b], -2, -3) == -2) { + const int k = atomicAdd(&s_wc, 1); + if (k < slots) miss_block[k] = b; + } + } + } + __syncthreads(); + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + if (res[b] == -3) res[b] = -2; + } + } + __syncthreads(); + /* `claims` ids, padded to a power of two: the row's scratch is sized for exactly + * that (r4d_rad_kv_resolve_scratch). */ + kv_sort_claims(miss_block, claims, tid); + } else { + /* More claims than the ring can hold: this call has overflowed whatever it places, + * so the sweep stops at its first unplaceable miss and `ctl[3]` latches. The list + * here is `blocks`-wide because the ascending order of the WHOLE claim set is the + * contract, and with no structure able to hold it the map is where it lives. A legal + * call -- one the ring can hold -- never reaches this. */ + const int chunk = (blocks + kThreads - 1) / kThreads; + const int lo = (int)((long long)tid * chunk); + const int hi = lo + chunk < blocks ? lo + chunk : blocks; + const bool vec4 = (lo & 3) == 0 && (hi & 3) == 0 && ((uintptr_t)res & 15u) == 0; + int c = 0; + if (vec4) { + const int4* const r4 = (const int4*)res; + for (int i = lo / 4; i < hi / 4; ++i) { + const int4 v = r4[i]; + c += (v.x == -2) + (v.y == -2) + (v.z == -2) + (v.w == -2); + } + } else { + for (int b = lo; b < hi; ++b) c += (res[b] == -2); + } + s_cnt[tid] = c; + s_off[tid] = c; + __syncthreads(); + for (int step = 1; step < kThreads; step <<= 1) { + const int v = tid >= step ? s_off[tid - step] : 0; + __syncthreads(); + s_off[tid] += v; + __syncthreads(); + } + __syncthreads(); + int pos = s_off[tid] - s_cnt[tid]; + if (vec4) { + const int4* const r4 = (const int4*)res; + for (int i = lo / 4; i < hi / 4; ++i) { + const int4 v = r4[i]; + if (v.x == -2 && pos < slots) miss_block[pos++] = 4 * i; + if (v.y == -2 && pos < slots) miss_block[pos++] = 4 * i + 1; + if (v.z == -2 && pos < slots) miss_block[pos++] = 4 * i + 2; + if (v.w == -2 && pos < slots) miss_block[pos++] = 4 * i + 3; + } + } else { + for (int b = lo; b < hi; ++b) + if (res[b] == -2 && pos < slots) miss_block[pos++] = b; + } + __syncthreads(); + } + } + if (tid == 0) { + /* The list is the first `want` claims in ascending order whichever path built it. */ + s_nmiss = want; + s_overflow = claims > slots; + s_placed = 0; + } + __syncthreads(); + } + + /* ---- 3b. how many slots are free ---- */ + /* A free slot is claimed before any resident block is evicted (phase 4), and this is what says + * whether there is one to claim: a call whose ring is full -- where every slot holds a block -- + * must not pay a turn of scanning per miss to discover it, and above that a full ring never + * becomes free again during the call. Counting in parallel costs one coalesced pass over the + * two slot maps; the sweep then reads the count and, when it is zero, goes straight to CLOCK. + * A slot this call stamped is not free whatever it holds: it is the call's own. */ + if (claims > 0) { + int nf = 0; + for (int s = tid; s < slots; s += kThreads) + if (slot_block[s] < 0 && slot_state[(size_t)s * sst_ld] != epoch) ++nf; + if (nf != 0) atomicAdd(&s_free, nf); + } + __syncthreads(); + + /* ---- 4. one victim per miss: the block's own slot first, else a free slot, else CLOCK ---- */ + /* Identity first: a block whose id fits the ring and whose own slot is free goes there, so + * res[b] = b for a context shorter than the ring. The attention's gather is a long run of + * adjacent block ids, and a layer's slots are 2 KiB apart inside one stripe, so identity turns + * that run into a sequential walk of one stripe instead of the order the blocks entered the + * selection. + * + * It is only a placement preference, never a replacement one: it takes a slot only when that + * slot is free, and it does not move the hand, so a ring that cannot give identity the slot + * falls through to the walk below with the hand exactly where it was. The fallback is free slot + * first, then CLOCK, so a depth where most ids are past `slots` places the same blocks in the + * same slots. + * + * A free slot (nothing resident in it) is not a victim at all: taking it costs no block, so + * every free slot is claimed before a live one is even considered. CLOCK's second chance over + * the heat counter is what a ring with no free slot falls back to, and the free scan has no + * side effect when it finds nothing (it halves no counter and leaves the hand where it + * started), so a full ring takes exactly the victim the sweep below names. + * + * `free_left` is the call's free-slot count from phase 3b, decremented as the sweep fills one. + * Once it is zero nothing can free a slot -- a placement makes a free slot live and an eviction + * re-points a live one -- so a full ring pays the count once, not a scan per miss. */ + if (tid == 0 && claims > 0) { + int hand = ctl[1]; + /* A hand outside the ring is a state fault libref refuses; start at the beginning + * rather than address outside it. */ + if (hand < 0 || hand >= slots) hand = 0; + int placed = 0; + bool overflow = s_overflow; + int free_left = s_free; + const int nmiss = s_nmiss; + for (int k = 0; k < nmiss; ++k) { + const int b = miss_block[k]; + int victim = -1; + /* Identity: the block's own slot, if the id fits the ring and the slot is free (or + * already holds it). Leaving the hand alone is what keeps the fallback identical. */ + if (b < slots) { + const int want = b; + if (slot_state[(size_t)want * sst_ld] != epoch && + (slot_block[want] < 0 || slot_block[want] == b)) + victim = want; + } + /* Free first, in the same hand order CLOCK walks, so a ring with frees to give + * places every miss identically in both implementations. A stamp of this call's epoch + * is never taken, free or not: it is a slot the call itself already uses. */ + if (victim < 0 && free_left > 0) { + int h = hand; + for (int scanned = 0; scanned < slots; ++scanned) { + const int s = h; + h = h + 1 == slots ? 0 : h + 1; + if (slot_state[(size_t)s * sst_ld] == epoch) continue; /* used by this call */ + if (slot_block[s] >= 0) continue; /* holds a block */ + victim = s; + hand = h; + break; + } + if (victim < 0) free_left = 0; + } + if (victim < 0) { + for (long long scanned = 0; scanned < 3LL * slots; ++scanned) { + const int s = hand; + hand = hand + 1 == slots ? 0 : hand + 1; + if (slot_state[(size_t)s * sst_ld] == epoch) continue; /* used by this call */ + const int old = slot_block[s]; + if (old >= 0 && old < blocks && + slot_state[(size_t)s * sst_ld + 1] > 0) { /* second chance */ + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_down(slot_state[(size_t)s * sst_ld + 1]); + continue; + } + victim = s; + break; + } + } + if (victim < 0) { overflow = true; break; } + /* ---- 5. re-point both maps ---- */ + const int s = victim; + const int old = slot_block[s]; + if (old < 0 && free_left > 0) --free_left; /* a free slot the sweep just filled */ + if (old >= 0 && old < blocks) res[old] = -1; + slot_block[s] = b; + slot_state[(size_t)s * sst_ld] = epoch; + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_up(slot_state[(size_t)s * sst_ld + 1]); + res[b] = s; + miss_slot[k] = s; + ++placed; + } + ctl[1] = hand; + ctl[2] = placed; + if (overflow) ctl[3] = 1; + s_placed = placed; + } + __syncthreads(); + + /* A miss the sweep could not place is not resident: undo every remaining claim, so the next + * call may claim them again. A `res` entry still -2 here is by definition such a claim (a + * placed one holds its slot), and every claim is named by at least one selection entry, so the + * selection reaches all of them: `lookups` entries instead of `blocks` map entries, and the + * write is idempotent, so an entry repeating a block is harmless. The list is the shorter pass + * when it holds every claim, which is the normal case. */ + if (claims > 0) { + if (s_distinct <= slots) { + for (int k = tid; k < s_distinct; k += kThreads) + if (res[miss_block[k]] == -2) res[miss_block[k]] = -1; + } else { + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + if (res[b] == -2) res[b] = -1; + } + } + } + } + __syncthreads(); + + /* ---- 6. the copies, one block each, in miss order, in this launch ---- */ + /* One warp a miss, so every miss's host read is in flight at once and each warp's lanes are + * independent. One 2 KiB copy out of the host mirror is PCIe transactions at ~1 us of latency + * each, and a decode launch takes tens of them: a loop that waits out one miss at a time, or a + * flattened loop that re-reads `miss_block`/`miss_slot` from the scratch for every lane, spends + * the launch waiting. The copies are independent -- each writes its own slot -- so the order + * between them is the miss order only for the record. + * + * Four loads per thread, issued before any of them is stored from. A wave issues in order and a + * store waits on its load, so `dst[i] = src[i]` at a stride of 32 makes the next iteration's load + * wait behind the previous iteration's store and the 2 KiB copy pays the mirror's read latency + * four times over instead of once (the trip count is `block_bytes`, a runtime value, so the + * compiler cannot unroll it). Loading the four vectors of one thread's quarter of the block + * first puts four requests in flight, and a block is + * a whole number of them at the declared geometry (2 KiB = 128 vectors = one full turn of the + * group), so the common path never takes the tail. Four more VGPRs: the kernel goes 32 -> 36 + * with no spill, and it runs one workgroup by design. + * + * The vectors are `kv_v16`, not `uint4`: that class's assignment is a 16-byte memcpy call, and a + * memcpy is a load and a store that are adjacent by construction however the four are written in + * the source, which is the serialised shape this loop exists to avoid. Builtin vectors leave the + * four as four loads and four stores, which is what the scheduler needs. Same bytes either way. */ + const int placed = s_placed; + const int lane = tid & 31; + if (bbytes >= 16 && bbytes % 16 == 0) { + const int vec = bbytes / 16; + for (int k = tid >> 5; k < placed; k += kThreads / 32) { + const kv_v16* __restrict__ const src = + (const kv_v16*)host + (size_t)miss_block[k] * vec; + kv_v16* __restrict__ const dst = (kv_v16*)cache + (size_t)miss_slot[k] * vec; + int i = lane; + for (; i + 96 < vec; i += 128) { + const kv_v16 a = src[i], b = src[i + 32], c = src[i + 64], d = src[i + 96]; + dst[i] = a; + dst[i + 32] = b; + dst[i + 64] = c; + dst[i + 96] = d; + } + /* A block that is not a whole number of four-wide turns -- `block_bytes` not a multiple + * of 2048 -- finishes at the original one-vector stride, so every lane sequence is + * covered exactly once whatever the pitch. */ + for (; i < vec; i += 32) dst[i] = src[i]; + } + } else { + for (int k = tid >> 5; k < placed; k += kThreads / 32) { + const uint8_t* src = host + (size_t)miss_block[k] * bbytes; + uint8_t* const dst = cache + (size_t)miss_slot[k] * bbytes; + for (int i = lane; i < bbytes; i += 32) dst[i] = src[i]; + } + } + + /* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */ + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const size_t e = (size_t)q * pitch + i; + const int b = sel[e]; + if ((unsigned)b >= (unsigned)blocks) continue; + /* A hit's slot is the one step 2 read; anything absent then (-1, -2, -3) only the map + * knows where the sweep placed it. Same index, same thread, so no barrier is needed. */ + int s = ecache > 0 ? s_ent[e] : -1; + if (s < 0) s = res[b]; + sel[e] = s >= 0 ? s : 0; + } + } + + /* The distinct blocks this call touched, for the union the caller reports: the slots this call + * hit or filled (counted in phase 2 and by the sweep) plus the claims it could not place. Both + * halves are known by now -- distinct hit slots and distinct claimed blocks -- and an entry + * count would overcount them, because many of a launch's rows share swaths of the history. + * Nothing walks the ring for it. */ + if (tid == 0) { + const int placed = s_placed; + const int uni = s_hits + s_distinct; + if (uni > ctl[10]) ctl[10] = uni; + if (placed > ctl[11]) ctl[11] = placed; + /* The depth the claim list had to hold, which is what the next size of it is derived from. */ + if (s_distinct > ctl[12]) ctl[12] = s_distinct; + uint64_t* const ctr = (uint64_t*)(ctl + 4); + ctr[0] += (uint64_t)placed; + ctr[1] += (uint64_t)s_lookups; + ctr[2] += 1u; + ctl[0] = epoch; + } +} + +} // namespace + +/* `sel` [M][sel_pitch] i32, block ids in, ring slots out + * `nsel` [M] i32, valid entries of each row + * `res` [blocks] i32, block -> slot, -1 absent, -2 claimed by this call + * `slot_block` [slots] i32, slot -> block, -1 free + * `slot_state` [slots][sst_ld] i32, [s][0] epoch of last use, [s][1] two-bit heat counter + * `ctl` [16] i32, [0] epoch, [1] hand, [2] placed, [3] overflow, u64 from [4] + * `host` [blocks][bbytes] u8, the layer's host mirror + * `cache` [slots][bbytes] u8, the layer's device ring + * `miss_block`, `miss_slot` the row scratch, `next_pow2(slots)` ids then `slots` slots + * `cap` the claim list's capacity, from kv_claim_cap + * `ecache` the entry cache's capacity in ints: `M * sel_pitch`, or 0 when + * the claim list leaves no room for it (header, "the entry cache") + * + * The two planes are addressed by `bbytes` alone, so the shim has already checked that each + * block's row pitch in bytes is exactly `block_bytes` and that its trailing extents fill it. */ +static int r4d_kv_resolve_emit(long sel, long nsel, long res, long slot_block, long slot_state, + long ctl, long host, long cache, long miss_block, long miss_slot, + int M, int blocks, int slots, int pitch, int bbytes, int sst_ld, + RadStream stream) { + if (!sel || !nsel || !res || !slot_block || !slot_state || !ctl || !host || !cache || + !miss_block || !miss_slot) + return R4D_NO(RAD_E_INVAL); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0 || sst_ld < 2) + return R4D_NO(RAD_E_SHAPE); + /* The list is sized from this launch's own operands. A workgroup with no LDS room for even one + * id cannot run the op at all, which is a shape the caller cannot satisfy rather than a slow + * launch: refuse it. */ + int room = 0; + const int cap = kv_claim_cap(M, pitch, &room); + if (cap < 1) return R4D_NO(RAD_E_SHAPE); + /* One int a selection entry for the entry cache (the header), while the room the claim list + * leaves holds them all: a decode launch caches its 513, a prefill this wide does not and step 7 + * reads the map again. */ + const long long entries = (long long)M * pitch; + const int ecache = entries <= (long long)(room - cap) ? (int)entries : 0; + return R4D_EMIT(stream, kv_resolve_kernel, dim3(1), dim3(kThreads), + (uint32_t)(cap + ecache) * sizeof(int), + (int32_t*)sel, (const int32_t*)nsel, (int32_t*)res, (int32_t*)slot_block, + (int32_t*)slot_state, (int32_t*)ctl, (const uint8_t*)host, (uint8_t*)cache, + (int32_t*)miss_block, (int32_t*)miss_slot, M, blocks, slots, pitch, + bbytes, sst_ld, cap, ecache); +} + +/* ============================================================== the plugin ABI entry point */ + +enum { KR_SEL = 0, KR_NSEL = 1, KR_RES = 2, KR_SBLK = 3, KR_SST = 4, KR_CTL = 5, KR_HOST = 6, + KR_CACHE = 7 }; + +/* Fan a byte extent into the shape's trailing elements: one block a row, dense, so the row pitch + * in bytes and the product of the trailing extents' element bytes both equal `block_bytes`. */ +static int r4d_kv_block_row_bytes(const RadTensor* t, long long* out) { + long long acc = 1; + for (unsigned d = 1; d < t->rank; ++d) acc *= t->shape[d]; + *out = acc * (long long)rad_dtype_bytes(t->dtype, 1); + return t->stride[0] * (long long)rad_dtype_bytes(t->dtype, 1) == *out ? RAD_OK : RAD_E_STRIDE; +} + +extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) { + const RadTensor* se = r4d_opt(a, KR_SEL); + const RadTensor* ns = r4d_opt(a, KR_NSEL); + const RadTensor* re = r4d_opt(a, KR_RES); + const RadTensor* sb = r4d_opt(a, KR_SBLK); + const RadTensor* st = r4d_opt(a, KR_SST); + const RadTensor* ct = r4d_opt(a, KR_CTL); + const RadTensor* ho = r4d_opt(a, KR_HOST); + const RadTensor* ca = r4d_opt(a, KR_CACHE); + if (!se || !ns || !re || !sb || !st || !ct || !ho || !ca) + return R4D_NO(RAD_E_INVAL); + + /* `M` is a RANGED parameter, so the resolved geometry carries the band's ceiling (max_tok), + * not this launch's rows: a 625-token prefill and a one-row decode both arrive with 2048 here. + * The operand names the call, as arch/common/rad_arch.h's "step-sized operands" rule says, so + * the row count is `sel`'s own extent and the parameter is only the ceiling it may not pass. */ + const long long band = r4d_geti_or(a, "M", 0); + const long long M = se->shape[0]; + const long long blocks = r4d_geti_or(a, "blocks", 0); + /* The ring depth is the operand's, for the same reason: the pool is planned after declare, so + * the declared `slots` is the context bound and a ring the engine sized smaller + * (--kv-resident) arrives as a shorter `slot_block`. The parameter is the ceiling a + * call may not pass (libref/ref_kvstream.cpp, "The parameters"). */ + const long long slots_decl = r4d_geti_or(a, "slots", 0); + const long long slots = sb->shape[0]; + /* The row pitch is the operand's too. Reading it from `sel_pitch` would let a view whose rows + * are wider or narrower than its declared geometry be rewritten into its neighbour. */ + const long long declared_pitch = r4d_geti_or(a, "sel_pitch", 0); + const long long pitch = r4d_row_pitch(se); + const long long bbytes = r4d_geti_or(a, "block_bytes", 0); + if (M <= 0 || blocks <= 0 || slots <= 0 || slots > slots_decl || pitch <= 0 || bbytes <= 0) + return R4D_NO(RAD_E_SHAPE); + if (M > INT32_MAX || blocks > INT32_MAX || slots > INT32_MAX || pitch > INT32_MAX || + bbytes > INT32_MAX) + return R4D_NO(RAD_E_SHAPE); + /* A launch above the band was resolved against constraints it does not satisfy. */ + if (band > 0 && M > band) return R4D_NO(RAD_E_SHAPE); + if (declared_pitch > 0 && pitch != declared_pitch) return R4D_NO(RAD_E_STRIDE); + + /* The map and the counts are one format, written by one op and read by the writer and the + * sweep: i32, dense. */ + const RadTensor* state[] = { se, ns, re, sb, st, ct }; + for (const RadTensor* t : state) + if (t->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (se->rank != 2 || st->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (se->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(ns) < M || ns->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(re) < blocks || re->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (sb->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (st->shape[0] < slots || st->stride[1] != 1 || st->stride[0] < 2) + return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(ct) < 16 || ct->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (ho->rank < 2 || ca->rank < 2) return R4D_NO(RAD_E_SHAPE); + if (ho->shape[0] < blocks || ca->shape[0] < slots) return R4D_NO(RAD_E_SHAPE); + + /* One block of one layer: the mirror's row and the pool's slot are the same bytes, and the + * copy length `block_bytes` is both pitches. The pool arrives as a KV group's cache, so its + * dtype is the cache layout's, not u8; only the byte pitch is fixed. */ + long long hdense = 0, pdense = 0; + if (r4d_kv_block_row_bytes(ho, &hdense) != RAD_OK || hdense != bbytes) + return R4D_NO(RAD_E_STRIDE); + if (r4d_kv_block_row_bytes(ca, &pdense) != RAD_OK || pdense != bbytes) + return R4D_NO(RAD_E_STRIDE); + /* The counters are read as u64 in an i32 block. */ + if (((uintptr_t)ct->data & 7u) != 0) return R4D_NO(RAD_E_STRIDE); + + /* The row's scratch: `nlist` ids (the miss list, padded to a power of two when a wide launch + * sorts it there), then `slots` slots. */ + const int64_t nlist = kv_pow2ceil(slots); + const long long need = (nlist + slots) * 4; + if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_INVAL); + int32_t* const miss_block = (int32_t*)a->scratch; + int32_t* const miss_slot = (int32_t*)((char*)a->scratch + nlist * 4); + + return r4d_kv_resolve_emit(r4d_addr(se), r4d_addr(ns), r4d_addr(re), r4d_addr(sb), + r4d_addr(st), r4d_addr(ct), r4d_addr(ho), r4d_addr(ca), + (long)(uintptr_t)miss_block, (long)(uintptr_t)miss_slot, + (int)M, (int)blocks, (int)slots, (int)pitch, (int)bbytes, + (int)st->stride[0], stream); +} + +/* The miss list -- `next_pow2(slots)` block ids, because a launch too wide for the shared claim list + * sorts the list in this scratch -- then `slots` slots (the header above). */ +extern "C" int64_t r4d_rad_kv_resolve_scratch(const RadArgs* a) { + const long long slots = r4d_geti_or(a, "slots", 0); + if (slots <= 0 || slots > INT32_MAX) return 0; + return (kv_pow2ceil(slots) + slots) * 4; +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 74355602..0a67c3d6 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -688,6 +688,94 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( } } +// The store of a streamed KV group: `kv_store_fp8` into the group's two copies. +// +// A streamed group's ring is `slots` blocks deep while its block-id space is `blocks`, so a block's +// id is not an address. Its host mirror is: +// +// host[blocks, kv_heads, block_size, 2 * head_dim] one block a row, identity layout +// +// and this kernel writes a token's k and v into the mirror's block `slot / block_size` ALWAYS, and +// into the ring at `res[block]` only when the map says the block is resident. Both planes have the +// same row pitch, so one offset serves both and the two copies cannot disagree. +// +// The residency test is here, not in the resolve, because the block a decode step writes is +// usually the one the previous step already made resident: a mirror-only writer would leave the +// ring's copy of that block short of this step's tokens, and the resolve does not re-copy a +// resident block. The caller orders store, then resolve, then attention, so a block that is NOT +// resident yet gets this step's bytes through the mirror and is copied in whole by the resolve. +// +// STATE FAULTS. libref refuses a slot naming a block past the id space and a map entry outside +// [-1, slots) before writing anything. A device launch cannot return a host status, so this kernel +// guards: a token whose block is out of range stores nothing, and a map entry outside its domain +// reads as not resident (the mirror is still written, and the resolve refuses the step). A legal +// call never takes either path and is bit-identical to the reference. +template +__global__ __launch_bounds__(kThreads) void kv_store_streamed_kernel( + const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, + const int32_t* __restrict__ res, uint8_t* __restrict__ host, + uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t blocks, uint32_t slots, + uint32_t k_ld, uint32_t v_ld, float k_inv, float v_inv) { + const uint32_t t = blockIdx.x; + const int32_t s = slot[t]; + if (s < 0) return; + const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size; + if (blk >= blocks) return; + /* Both planes are byte planes of the same paged layout; a bf16 element is two bytes, so every + * offset and pitch doubles while the row arithmetic stays one expression. */ + const size_t EB = BF16 ? 2 : 1; + const size_t row = (size_t)kv_heads * block_size * 2 * head_dim * EB; + const size_t so = (size_t)off * 2 * head_dim * EB; + uint8_t* const m = host + (size_t)blk * row + so; + const int32_t sl = res[blk]; + /* A map entry outside [-1, slots) is not an address: treat it as absent. */ + uint8_t* const c = (sl >= 0 && (uint32_t)sl < slots) ? kv + (size_t)sl * row + so : nullptr; + const size_t head_step = (size_t)block_size * 2 * head_dim * EB; + + for (uint32_t j = threadIdx.x * 4u; j < kv_heads * head_dim; j += kThreads * 4u) { + const uint32_t h = j / head_dim, d = j % head_dim; + uint8_t* const mrow = m + (size_t)h * head_step; + uint8_t* const crow = c ? c + (size_t)h * head_step : nullptr; + float kf[4], vf[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv; + vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv; + } + if constexpr (BF16) { + /* kv_store_bf16's bytes: the value itself, no descales (k_inv/v_inv are 1). */ + uint16_t* const mk = (uint16_t*)mrow; + uint16_t* const mv = (uint16_t*)(mrow + (size_t)head_dim * 2); + uint16_t* const ck = crow ? (uint16_t*)crow : nullptr; + uint16_t* const cv = crow ? (uint16_t*)(crow + (size_t)head_dim * 2) : nullptr; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const uint16_t kb = f32_to_bf16(kf[e]), vb = f32_to_bf16(vf[e]); + mk[d + e] = kb; + mv[d + e] = vb; + if (ck) { ck[d + e] = kb; cv[d + e] = vb; } + } + } else { + int pk = 0, pv = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[0], -448.0f), 448.0f), + fminf(fmaxf(kf[1], -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[2], -448.0f), 448.0f), + fminf(fmaxf(kf[3], -448.0f), 448.0f), pk, true); + pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf[0], -448.0f), 448.0f), + fminf(fmaxf(vf[1], -448.0f), 448.0f), pv, false); + pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf[2], -448.0f), 448.0f), + fminf(fmaxf(vf[3], -448.0f), 448.0f), pv, true); + *(uint32_t*)(mrow + d) = (uint32_t)pk; + *(uint32_t*)(mrow + head_dim + d) = (uint32_t)pv; + if (crow) { + *(uint32_t*)(crow + d) = (uint32_t)pk; + *(uint32_t*)(crow + head_dim + d) = (uint32_t)pv; + } + } + } +} + // The fp8_v4 store: K as kv_store_fp8 writes it, V as int4 in groups of 32 with an f16 scale // (absmax / 7). Four columns a thread as above, so a group of 32 is 8 lanes; head_dim is a multiple // of 32, so a group never straddles two heads. A token's row is `row` bytes. K6 is the k6_v4 store: @@ -2220,6 +2308,70 @@ static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) { extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); } extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); } +/* The store of a streamed group: `kv_store`'s geometry and E4M3 conversion, plus the group's + * residency map (`res`) and its host mirror (`host`). The mirror is the truth and is written for + * every token with a slot; the ring is written only when `res[block] >= 0`. Both are one block a + * row of the same byte pitch, so the row arithmetic is the cache's, unchanged. + * + * `res` is read, never written: residency is the resolve's decision, and this op must not move the + * map under a selection the indexer already resolved. A block id past the mirror's extent or a map + * entry outside [-1, slots) is a state fault that libref refuses; the kernel guards instead (see + * kv_store_streamed_kernel), since a device launch cannot return a host status. + * + * The cache is E4M3 or bf16. Streaming is dtype-agnostic beyond the two writers: the mirror and the + * ring are byte planes of one paged layout whose pitch is `block_bytes`, so a bf16 group doubles + * every offset and stores the values kv_store_bf16 stores. */ +extern "C" int r4d_rad_kv_store_streamed(const RadArgs* a, RadStream stream) { + KvStoreGeom g{}; + const int rc = kv_store_geom(a, &g); + if (rc != RAD_OK) return rc; + if (g.kv->dtype != RAD_F8E4M3 && g.kv->dtype != RAD_BF16) + return R4D_NO(RAD_E_UNSUPPORTED); + /* Four columns per thread, so a head must be whole groups. */ + if (g.head_dim % 4) return R4D_NO(RAD_E_SHAPE); + + const RadTensor* res = r4d_opt(a, 4); + const RadTensor* host = r4d_opt(a, 5); + if (!res || !host) return R4D_NO(RAD_E_INVAL); + if (res->dtype != RAD_I32 || !r4d_contig(res)) return R4D_NO(RAD_E_STRIDE); + if (host->dtype != RAD_U8 || !r4d_contig(host) || host->rank != 2) + return R4D_NO(RAD_E_STRIDE); + + const long long row = g.kv_heads * g.block_size * 2 * g.head_dim * + (g.kv->dtype == RAD_BF16 ? 2 : 1); + const long long blocks = host->shape[0], slots = g.kv->shape[0]; + if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE); + /* Both planes are dense rows of one block, so the same offset addresses the same element. */ + if (host->shape[1] != row || host->stride[0] != row) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE); + + const double ks = r4d_getf(a, "k_scale", 1.0); + const double vs = r4d_getf(a, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + + const long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim; + const long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim; + const bool bf16 = g.kv->dtype == RAD_BF16; + /* kv_store_bf16 stores the value itself, so a bf16 group uses no descales. */ + const float k_inv = bf16 ? 1.0f : (float)(1.0 / ks); + const float v_inv = bf16 ? 1.0f : (float)(1.0 / vs); + if (bf16) + return R4D_EMIT(stream, kv_store_streamed_kernel<1>, dim3((uint32_t)g.T), dim3(kThreads), + 0, (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (const int32_t*)r4d_addr(res), (uint8_t*)r4d_addr(host), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)blocks, (uint32_t)slots, (uint32_t)k_ld, (uint32_t)v_ld, + k_inv, v_inv) == RAD_OK ? RAD_OK : RAD_E_DEVICE; + return R4D_EMIT(stream, kv_store_streamed_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0, + (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (const int32_t*)r4d_addr(res), (uint8_t*)r4d_addr(host), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)blocks, (uint32_t)slots, (uint32_t)k_ld, (uint32_t)v_ld, + k_inv, v_inv) == RAD_OK ? RAD_OK : RAD_E_DEVICE; +} + /* ------------------------------------------------------------------ logits_gemm * * gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above). diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 87d99131..61da0830 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -521,6 +521,7 @@ int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gdn_gated_norm_hq_i8 (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream); +int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs*, RadStream); int r4d_rad_rope_table (const RadArgs*, RadStream); @@ -557,6 +558,9 @@ int r4d_rad_qsa_block_key (const RadArgs*, RadStream); int r4d_rad_qsa_score (const RadArgs*, RadStream); int r4d_rad_qsa_select (const RadArgs*, RadStream); int64_t r4d_rad_qsa_select_scratch(const RadArgs*); +int r4d_rad_kv_resolve (const RadArgs*, RadStream); +int64_t r4d_rad_kv_resolve_scratch(const RadArgs*); +int r4d_rad_kv_store_streamed(const RadArgs*, RadStream); int r4d_rad_qsa_tail_store (const RadArgs*, RadStream); int r4d_rad_qsa_work (const RadArgs*, RadStream); int r4d_rad_sample_chain (const RadArgs*, RadStream); @@ -819,6 +823,7 @@ int r4d_shape_fill (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_silu_mul (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rope (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_kv_store (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_kv_store_streamed (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_logits_gemm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_sample_penalties (const RadParam*, int, int operand, RadOpdDesc*); @@ -839,6 +844,8 @@ int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadO int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qk_norm_rope_gate_kv_store_streamed(const RadParam*, int, int operand, + RadOpdDesc*); int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); @@ -884,6 +891,7 @@ int r4d_shape_gram_accum (const RadParam*, int, int operand, RadOpdDesc* int r4d_shape_qsa_block_key (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_score (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_select (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_kv_resolve (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_tail_store (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_work (const RadParam*, int, int operand, RadOpdDesc*); @@ -913,6 +921,8 @@ int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadF int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam*, int, uint64_t, int, + RadFuseStep*); int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 9274a31f..43598c1e 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -50,10 +50,18 @@ struct QkKvStore { int v_pitch, block_size, n_blocks; float k_inv, v_inv; int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */ + /* QK_KV_STREAMED only: the group's host mirror and per-layer residency map, as + * kv_store_streamed takes them (libr4d/r4d_model_bf16.hip). `blocks` is the mirror's block + * count (the id space) while `n_blocks` stays the ring depth. */ + const int32_t* res; + void* host; + int blocks; }; -/* The cache forms KV selects. */ -enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4 }; +/* The cache forms KV selects. The two STREAMED forms are the same store with two destination + * planes: E4M3 (the fp8 QSA family) and bf16 (the default cache dtype). */ +enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4, + QK_KV_STREAMED = 5, QK_KV_STREAMED_BF16 = 6 }; /* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also * writes that element and the head's v element into the cache at the token's slot, as E4M3 with @@ -151,7 +159,56 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( if constexpr (KV != QK_KV_NONE) { if (isk && t < HD) { const int32_t sl = kvs.slot[tok]; - if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) { + /* A streamed group's cache is the ring and its truth is the host mirror: the token goes to + * the mirror's block row ALWAYS and to the ring slot only where the residency map says the + * block is resident, exactly as kv_store_streamed writes it (libref/ref_attn.cpp states why + * the test belongs in the writer). The block id bounds the mirror, the map bounds the ring, + * and a slot names a ring block only through `res`. */ + if constexpr (KV == QK_KV_STREAMED || KV == QK_KV_STREAMED_BF16) { + if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.blocks) { + const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size; + const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size; + /* One element of each plane. The mirror and the ring are byte planes of the same paged + * layout and `block_bytes` is their pitch, so a bf16 element is two bytes at twice the + * fp8 offset. */ + const size_t EB = KV == QK_KV_STREAMED_BF16 ? 2 : 1; + const size_t rowb = (size_t)(2 * HD) * EB; + const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb + + (size_t)lh * kvs.block_size * rowb; + const __hip_bfloat16 kb = __float2bfloat16(res); + const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t]; + const int32_t rs = kvs.res[blk]; + unsigned char* const m = (unsigned char*)kvs.host + at; + unsigned char* const c = + (rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks) + ? (unsigned char*)kvs.cache + + (((size_t)rs * nkv * kvs.block_size + off) * rowb + + (size_t)lh * kvs.block_size * rowb) + : nullptr; + if constexpr (KV == QK_KV_STREAMED_BF16) { + /* kv_store_bf16 writes the values themselves: no descales. */ + *(__hip_bfloat16*)(m + EB * t) = kb; + *(__hip_bfloat16*)(m + EB * (HD + t)) = vb; + if (c) { + *(__hip_bfloat16*)(c + EB * t) = kb; + *(__hip_bfloat16*)(c + EB * (HD + t)) = vb; + } + } else { + const float kf = __bfloat162float(kb) * kvs.k_inv; + const float vf = __bfloat162float(vb) * kvs.v_inv; + const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f, + 0, false); + const int pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f, + 0, false); + m[t] = (unsigned char)(pk & 0xFF); + m[HD + t] = (unsigned char)(pv & 0xFF); + if (c) { + c[t] = (unsigned char)(pk & 0xFF); + c[HD + t] = (unsigned char)(pv & 0xFF); + } + } + } + } else if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) { const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size; const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size; const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD); @@ -261,7 +318,7 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel( // The two launches, as the plugin ABI's RadLaunchFn. See the note at the head of // r4d_quant_act_i8.hip on the argument list and status return. enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK_GOUT, - QK_V, QK_SLOT, QK_CACHE }; + QK_V, QK_SLOT, QK_CACHE, QK_RES, QK_HOST }; /* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */ template @@ -386,6 +443,76 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream : qk_body(args, stream, kvs); } +/* The prologue with the STREAMED store folded in: a streamed group's cache is a ring of + * `n_blocks` slots over a `blocks`-wide block-id space, and its truth is the pinned host mirror. + * Each token's rotated k and its v go to the mirror's block row ALWAYS and to `kv_cache[res[block]]` + * only when the residency map calls the block resident (docs/OPS.md "kv_store_streamed"), so this + * row replaces `qk_norm_rope_gate` + `kv_store_streamed` with one launch a layer and one chain + * between store, resolve and attention. + * + * The bytes are the pair's exactly: `k_out`'s bf16 value is the one the E4M3 conversion reads, and + * both planes are the same dense rows of the same paged layout, so the folded write and the split + * write are the same arithmetic. The cache is E4M3 (the fp8 QSA family) or bf16 (the default + * `--kv-cache-dtype`, where both planes are the value itself, as kv_store_bf16 writes it). */ +extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) { + const RadTensor* k = r4d_opt(args, QK_K); + const RadTensor* qg = r4d_opt(args, QK_QGATE); + const RadTensor* v = r4d_opt(args, QK_V); + const RadTensor* sm = r4d_opt(args, QK_SLOT); + const RadTensor* kv = r4d_opt(args, QK_CACHE); + const RadTensor* res = r4d_opt(args, QK_RES); + const RadTensor* ho = r4d_opt(args, QK_HOST); + if (!k || !v || !sm || !kv || !res || !ho) return R4D_NO(RAD_E_INVAL); + const char* kvd = r4d_gets(args, "kv_dtype"); + const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID; + if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want || + (kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16) || res->dtype != RAD_I32 || + ho->dtype != RAD_U8) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(sm) || !r4d_contig(kv) || !r4d_contig(res) || !r4d_contig(ho) || + ho->rank != 2) + return R4D_NO(RAD_E_STRIDE); + + const long long hd = r4d_geti_or(args, "head_dim", 0); + const long long nkv = r4d_geti_or(args, "n_head_kv", 0); + const long long bs = r4d_geti_or(args, "block_size", 0); + if (hd <= 0 || nkv <= 0 || bs <= 0) return R4D_NO(RAD_E_SHAPE); + if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd) + return R4D_NO(RAD_E_SHAPE); + const long long M = qg ? qg->shape[0] : k->shape[0]; + long long Mv = 0; + const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); + if (v_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE); + + /* One block of one layer: the mirror's row pitch and the ring's slot pitch are the same bytes, + * so the store addresses both with one row arithmetic. */ + const long long row = nkv * bs * 2 * hd * (kv->dtype == RAD_BF16 ? 2 : 1); + const long long blocks = ho->shape[0], slots = kv->shape[0]; + if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE); + if (ho->shape[1] != row || ho->stride[0] != row) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE); + + const double ks = r4d_getf(args, "k_scale", 1.0); + const double vs = r4d_getf(args, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + + QkKvStore kvs{}; + kvs.v = (const __hip_bfloat16*)r4d_p(v); + kvs.slot = (const int32_t*)r4d_p(sm); + kvs.cache = r4d_wp(kv); + kvs.v_pitch = (int)v_ld; + kvs.block_size = (int)bs; + kvs.n_blocks = (int)slots; + kvs.k_inv = 1.0f / (float)ks; + kvs.v_inv = 1.0f / (float)vs; + kvs.res = (const int32_t*)r4d_p(res); + kvs.host = r4d_wp(ho); + kvs.blocks = (int)blocks; + return kv->dtype == RAD_BF16 ? qk_body(args, stream, kvs) + : qk_body(args, stream, kvs); +} + /* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size, * 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */ static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) { diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index be3ca727..5e611270 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -291,6 +291,25 @@ static const RadOperandSpec oQkNormRopeGateKv[] = { { "slot_mapping", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, }; +/* The prologue with a streamed group's store folded in: the same parameters and operands, then the + * residency map and the layer's host mirror, which the store needs and the ring does not. The cache + * is E4M3 only (streaming ships for the fp8 QSA family). */ +static const RadOperandSpec oQkNormRopeGateKvStreamed[] = { + { "q_gate", RAD_OPD_IN, 1 }, + { "k", RAD_OPD_IN, 0 }, + { "cos_sin", RAD_OPD_IN, 0 }, + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 1 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, + { "q_out", RAD_OPD_OUT, 1 }, + { "k_out", RAD_OPD_OUT, 0 }, + { "gate_out", RAD_OPD_OUT, 1 }, + { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, + { "res", RAD_OPD_IN, 0 }, + { "host", RAD_OPD_INOUT, 0 }, +}; /* Builds the cos/sin table the fused prologue reads, each position at its own row of a * [max_ctx, rot] plane. `rot`, `theta` and `scale` are spelled as `rope`'s, since both must compute * the same angles. */ @@ -1332,6 +1351,32 @@ static const RadOperandSpec oQsaSelect[] = { { "seqused", RAD_OPD_OUT, 0 }, }; +/* `kv_resolve`, a new op whose schema this plugin fixes: the residency map of a streamed KV + * group, between `qsa_select` and the attention. `sel` is block ids in and ring slots out; + * `res`, `slot_block`, `slot_state` and `ctl` are the state it keeps between calls, so its row is + * not concurrent. The miss list is the row's scratch, not an operand: nothing outside the launch + * reads it. `block_bytes` is a byte extent, not `block_size`: the op only moves bytes, and a + * `block_size` key would make it the KV group's consumer, taking the block size the resolved + * attention kernel must read. */ +static const RadParamSpec pKvResolve[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "blocks", RAD_P_INT, RAD_REQUIRED }, + { "slots", RAD_P_INT, RAD_REQUIRED }, + { "sel_pitch", RAD_P_INT, RAD_REQUIRED }, + { "block_bytes", RAD_P_INT, RAD_REQUIRED }, +}; +static const RadOperandSpec oKvResolve[] = { + { "sel", RAD_OPD_INOUT, 0 }, + { "nsel", RAD_OPD_IN, 0 }, + { "res", RAD_OPD_INOUT, 0 }, + { "slot_block", RAD_OPD_INOUT, 0 }, + { "slot_state", RAD_OPD_INOUT, 0 }, + { "ctl", RAD_OPD_INOUT, 0 }, + { "host", RAD_OPD_IN, 0 }, + /* The group's ring, the same RAD_KV operand `attn_paged` and `kv_store` take. */ + { "kv_cache", RAD_OPD_INOUT, 0 }, +}; + /* `qsa_score`, a new op whose schema this plugin fixes: the indexer's score of each compressed * block of key history for one query. * @@ -2041,6 +2086,27 @@ static const RadOperandSpec oKvStore[] = { { "slot_mapping", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, }; +/* `kv_store` for a streamed group. `host` is the group's authoritative mirror and is always + * written, `res` is the residency map that says whether the block is in the ring (the ring slot is + * written only when `res[block] >= 0`). The parameters are kv_store's: the layout and the E4M3 + * conversion are the same, only the destination set differs. */ +static const RadParamSpec pKvStoreStreamed[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + { "block_size", RAD_P_INT, RAD_REQUIRED }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("k_scale"), + P_F64O("v_scale"), +}; +static const RadOperandSpec oKvStoreStreamed[] = { + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, + { "res", RAD_OPD_IN, 0 }, + { "host", RAD_OPD_INOUT, 0 }, +}; static const RadParamSpec pEmbed[] = { { "M", RAD_P_INT, RAD_REQUIRED }, @@ -2913,6 +2979,13 @@ static const RadOpSchema kSchemas[] = { SCHEMA("kv_store", pKvStore, oKvStore, "scatter k and v into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim] -- K at " "[.., d] and V at [.., head_dim + d]. A negative slot stores nothing."), + SCHEMA("kv_store_streamed", pKvStoreStreamed, oKvStoreStreamed, + "kv_store for a streamed group: the token's k and v into the group's host mirror at the " + "BLOCK's identity row always, and into kv_cache[res[block]] only when the residency map " + "says the block is resident. The mirror is the truth and a block absent from the ring is " + "copied in whole by kv_resolve, so the caller orders store, then resolve, then " + "attention. A negative slot stores nothing; a map entry outside [-1, slots) is treated " + "as not resident, which libref refuses as a state fault."), SCHEMA("embed_lookup", pEmbedM, oEmbed, "the embedding gather. A negative token id writes a zero row, and so does one outside " "[vocab_offset, vocab_offset + n_vocab) -- which is what makes the table shardable " @@ -3046,6 +3119,13 @@ static const RadOpSchema kSchemas[] = { "qk_norm_rope_gate followed by kv_store, in one launch: each k head's block also writes " "its rotated k and its v into the paged cache at the token's slot. The `k` kv_store " "reads is `k_out`, so the tail adds only `v`, `slot_mapping` and `kv_cache`."), + SCHEMA("qk_norm_rope_gate_kv_store_streamed", pQkNormRopeGateKv, oQkNormRopeGateKvStreamed, + "qk_norm_rope_gate followed by kv_store_streamed, in one launch: the token's rotated k " + "and its v into the group's host mirror at the BLOCK's identity row always, and into " + "kv_cache[res[block]] only when the residency map says the block is resident. The " + "mirror is the truth and a block absent from the ring is copied in whole by kv_resolve, " + "so the caller keeps store, then resolve, then attention. Replaces the prologue plus a " + "separate streamed store, one launch a layer. E4M3 caches only."), SCHEMA("rope_table", pRopeTable, oRopeTable, "the cos/sin `qk_norm_rope_gate` reads, written at each position's OWN row of a " "[max_ctx, rot] plane: rot values a row, cos for the first half and sin for the second. " @@ -3344,6 +3424,20 @@ static const RadOpSchema kSchemas[] = { "nowhere else, so the effective query position is (nsel-1)*ratio + pos%ratio. Ties " "break to the LOWER block index through a prefix count, never through atomic order. " "`signed` 1 ranks signed finite scores; absent or 0 ranks max(score, 0)."), + SCHEMA("kv_resolve", pKvResolve, oKvResolve, + "make every block the selections name resident and rewrite them as ring slots: bump " + "the epoch, take a hit or make a single claim (-1 -> -2) per distinct block, compact " + "the claimed blocks in ASCENDING block id, take a free slot before any resident one and " + "otherwise one CLOCK second-chance victim per miss from ctl[1] -- a warm slot (two-bit " + "heat counter) is halved and passed, a cold one is taken, and a slot this call already " + "uses is never taken -- re-point both maps, copy " + "each missed block from the host mirror into its slot, then replace every entry below " + "nsel with the slot holding its block. nsel and the attention's length are unchanged. " + "The ring must hold the call's distinct blocks: a call that cannot place every miss " + "latches ctl[3], reverts the unplaced claims to -1 and leaves those entries naming " + "blocks, never a fabricated slot, so the caller must refuse the step. The maps, the " + "epoch, the hand and the heat counters keep state across launches, so the row is not " + "concurrent; the miss list is the row's scratch (2 * slots i32), not an operand."), SCHEMA("qsa_score", pQsaScore, oQsaScore, "score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[m][b]])) / sqrt(n). THE RELU IS " "PER (BLOCK, HEAD) AND THE SUM IS OVER HEADS, in that order -- four independent votes, " @@ -4609,6 +4703,12 @@ static const RadConstraint cQsaTailStore[] = { /* No dtype: every operand is f32 or i32. */ static const RadConstraint cQsaSelect[] = { C_GE("blocks", 1), C_GE("topk", 1), C_GE("ratio", 1) }; +/* The two byte planes are read by pitch, so only positivity is fixed: any block extent and any + * ring depth the device can address. */ +static const RadConstraint cKvResolve[] = { + C_GE("blocks", 1), C_GE("slots", 1), C_GE("sel_pitch", 1), C_GE("block_bytes", 1), +}; + /* A lane owns n/32 dims of both operands, so n is a wave multiple, at most eight of them. The * head bound is the register file: the query stays resident across the block loop. */ static const RadConstraint cQsaScore[] = { @@ -4785,6 +4885,14 @@ static const RadConstraint cQkNormRopeGateKv[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), }; +static const RadConstraint cQkNormRopeGateKvStreamed[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cQkNormRopeGateKvStreamedBf16[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cQkNormRopeGateKvFp8v4[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "fp8_v4"), @@ -5135,6 +5243,15 @@ static const RadConstraint cCausalConv[] = { C_IN("dtype", "bf16"), C_GE("width" C_LE("width", 8) }; static const RadConstraint cKvStore[] = { C_GE("block_size", 1), C_IN("kv_dtype", "bf16") }; static const RadConstraint cKvStoreFp8[] = { C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3") }; +/* The streamed store converts as the fp8 row does and requires the same divisible head. */ +static const RadConstraint cKvStoreStreamedFp8[] = { C_GE("block_size", 1), + C_IN("kv_dtype", "fp8_e4m3"), + C_DIV("head_dim", 4) }; +/* The same store into a bf16 cache: the mirror and the ring are the value itself, as kv_store_bf16 + * writes it. Head_dim needs only the four-column grouping. */ +static const RadConstraint cKvStoreStreamedBf16[] = { C_GE("block_size", 1), + C_IN("kv_dtype", "bf16"), + C_DIV("head_dim", 4) }; static const RadConstraint cKvStoreFp8v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), C_IN("kv_dtype", "fp8_v4") }; static const RadConstraint cKvStoreK6v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), @@ -5842,6 +5959,31 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_kv_store_k6v4, nullptr, nullptr, nullptr, nullptr }, +/* The store of a streamed KV group: the host mirror always, the ring slot when resident. One + * workgroup a token, two destinations; the mirror's row pitch is the block's, so a token's bytes + * land at the same offsets in both planes. */ +{ "kv_store_streamed_fp8", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the ring slot the residency map names", + "cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror [blocks, the same row pitch]; " + "head_dim a multiple of 4; a negative slot stores nothing", + "bf16 k / v, E4M3 mirror and ring, i32 slot mapping and residency map, scalar descales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreStreamedFp8), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_kv_store_streamed }, + +/* The same store into a bf16 cache: the mirror and the ring hold the values themselves, as + * kv_store_bf16 writes them, and every plane offset is two bytes wide. */ +{ "kv_store_streamed_bf16", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the ring slot the residency map names", + "cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror [blocks, the same row pitch as " + "bytes]; head_dim a multiple of 4; a negative slot stores nothing", + "bf16 k / v, bf16 mirror and ring, i32 slot mapping and residency map", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreStreamedBf16), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_kv_store_streamed }, + { "logits_gemm_bf16", "logits_gemm", "vocab", "the lm_head projection: C[M, n_vocab] f32 = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T", "any M and any vocabulary; n_embd a multiple of 8. One workgroup a vocabulary column", @@ -8018,6 +8160,21 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_qsa_select, r4d_rad_qsa_select_scratch, nullptr, nullptr, r4d_shape_qsa_select }, +/* The residency map of a streamed KV group. One workgroup: the CLOCK hand is serial state, and the + * phases are barriers over the entries, the block-id space and the ring. The copy is the same + * launch, so one step is one dispatch rather than one per claim. */ +{ "kv_resolve_i32", "kv_resolve", "attn", + "turn selected KV block ids into ring slots, evict by CLOCK and copy misses in from the host", + "any block count, ring depth and block byte extent; the mirror and the ring are read by byte " + "pitch, so every cache layout is the same launch", + "i32 selection and residency maps, u8 host mirror, the group's KV cache; the selection and both " + "maps are rewritten in place. A call that needs more distinct blocks than slots latches " + "ctl[3] and leaves those entries naming blocks, never a fabricated slot", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvResolve), NOTUNE, + nullptr, nullptr, r4d_rad_kv_resolve, r4d_rad_kv_resolve_scratch, nullptr, nullptr, + r4d_shape_kv_resolve }, + /* The indexer's score. One workgroup per query, one wave per block: a lane owns n/32 consecutive * dims of the query heads and the block key, so a head's dot product is one wave reduction and the * block key is read once for all heads (the head loop is inside the block loop). */ @@ -8491,6 +8648,35 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store, nullptr, nullptr, nullptr, r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store }, +/* The prologue and the STREAMED cache store in one launch: the mirror for every token, the ring + * only where the residency map says the block is resident. The operands are the pair's, plus the + * map and the mirror. */ +{ "qk_norm_rope_gate_kv_store_streamed_fp8", "qk_norm_rope_gate_kv_store_streamed", "attn", + "qk_norm_rope_gate, and kv_store_streamed (host mirror always, resident ring slot too) from the " + "same launch", + "qk_norm_rope_gate's shapes; cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror " + "[blocks, the same row pitch], one slot a row; a negative slot stores nothing", + "bf16 in and out, E4M3 mirror and ring, i32 slot mapping and residency map, scalar descales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvStreamed), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_qk_norm_rope_gate_kv_store_streamed, nullptr, + r4d_fuse_qk_norm_rope_gate_kv_store_streamed }, + +/* The same fold into a bf16 streamed group: the default `--kv-cache-dtype`, where both planes hold + * the rotated k and v themselves, as kv_store_streamed_bf16 writes them. */ +{ "qk_norm_rope_gate_kv_store_streamed_bf16", "qk_norm_rope_gate_kv_store_streamed", "attn", + "qk_norm_rope_gate, and kv_store_streamed (host mirror always, resident ring slot too) from the " + "same launch", + "qk_norm_rope_gate's shapes; cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror " + "[blocks, the same row pitch as bytes], one slot a row; a negative slot stores nothing", + "bf16 in and out, bf16 mirror and ring, i32 slot mapping and residency map", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvStreamedBf16), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_qk_norm_rope_gate_kv_store_streamed, nullptr, + r4d_fuse_qk_norm_rope_gate_kv_store_streamed }, + /* The fold into an fp8_v4 cache: E4M3 K, int4 V in groups of 32 (a wave) with f16 scales. */ { "qk_norm_rope_gate_kv_store_fp8v4", "qk_norm_rope_gate_kv_store", "attn", "qk_norm_rope_gate, and kv_store into an fp8_v4 paged cache from the same launch", @@ -9533,6 +9719,8 @@ extern "C" int rad_kernel_concurrent(int i) { if (k->family && std::strcmp(k->family, "ar") == 0) return 0; static const char* const kStateful[] = { "hc_", "mtp_enter", "ar_", "gemm_w4a8_tiled", "gemm_w8a8_tiled", "lora_", + /* The residency map's epoch, hand, heat counters and counters live across launches. */ + "kv_resolve", }; for (const char* p : kStateful) if (std::strncmp(k->name, p, std::strlen(p)) == 0) return 0; diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 35d281e5..ec9c509b 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -754,6 +754,33 @@ extern "C" int r4d_shape_kv_store(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* The streamed store: kv_store's geometry with the group's two copies beside the ring. One block + * and one ring slot, with every token on its own position of that block: the draw vocabulary cannot + * express an injective residency map, and two blocks drawing one slot would be a race between two + * tokens on one ring byte. The partly resident map and the mirror-only step are built by hand. */ +extern "C" int r4d_shape_kv_store_streamed(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + /* E4M3 or bf16: the mirror and the ring are byte planes of the same paged layout, and the + * mirror's row pitch doubles for a two-byte element. */ + if (KV != (uint32_t)RAD_F8E4M3 && KV != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd_idx(M, 0, bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping, one block */ + opd(KV, 1, kvh, bs, 2 * hd), /* kv_cache -- the ring */ + opd_idx(1, 0, 1, 0), /* res -- the block, resident in slot 0 */ + opd((uint32_t)RAD_U8, 1, row), /* host -- the layer's mirror */ + }; + R4D_PICK(l); +} + /* logits_gemm at bf16. The fp8 row is not described; see the file header. */ extern "C" int r4d_shape_logits_gemm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1133,6 +1160,35 @@ extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int R4D_PICK(l); } +/* qk_norm_rope_gate_kv_store_streamed -- the prologue's operands, then the streamed store's: `v`, + * `slot_mapping`, the ring, the residency map and the layer's mirror. One block, one ring slot and + * every token on its own position of it, exactly as kv_store_streamed's shape says (the draw + * vocabulary cannot express an injective block -> slot map, and two blocks in one slot would race). + * E4M3 or bf16: both planes are byte planes whose pitch is one block, so a bf16 mirror row is twice + * the fp8 row. */ +extern "C" int r4d_shape_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p, + int operand, RadOpdDesc* out) { + if (operand < 9) return r4d_shape_qk_norm_rope_gate(p, n_p, operand, out); + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + if (KV != (uint32_t)RAD_F8E4M3 && KV != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + const RadOpdDesc l[] = { + opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), + opd_none(), opd_none(), + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd_idx(M, 0, bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping, one block */ + opd(KV, 1, kvh, bs, 2 * hd), /* kv_cache -- the ring */ + opd_idx(1, 0, 1, 0), /* res -- the block, resident in slot 0 */ + opd((uint32_t)RAD_U8, 1, row), /* host -- the layer's mirror */ + }; + R4D_PICK(l); +} + /* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1869,6 +1925,34 @@ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* The residency map and the two byte planes. `sel` is described as block ids, which is what + * `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch. + * + * A described residency map can only be an all-resident one: the description vocabulary draws an + * index in [0, idx_max) or a constant, and a cold entry is -1, which no draw expresses. So a tool + * that calls this op cold sees every map entry at 0, which exercises the epoch, the rewrite and + * the bookkeeping but never a miss, an eviction or a copy. The service-shaped cases are built by + * hand in tests/ref_test.cpp and in this plugin's selftest, against libref. */ +extern "C" int r4d_shape_kv_resolve(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + + const int64_t M = pi(p, n_p, "M"), blocks = pi(p, n_p, "blocks"); + const int64_t slots = pi(p, n_p, "slots"), pitch = pi(p, n_p, "sel_pitch"); + const int64_t bbytes = pi(p, n_p, "block_bytes"); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0) + return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd_idx(M, pitch, blocks), /* sel -- one block id an entry */ + opd_idx(M, 0, pitch + 1), /* nsel -- 0 .. sel_pitch */ + opd_idx(blocks, 0, slots, 0), /* res -- an all-resident map, no -2 */ + opd_idx(slots, 0, blocks, 0), /* slot_block -- the reverse map */ + opd_idx(slots, 2, 2, 0), /* slot_state -- cold: epoch 0, no reference */ + opd_idx(16, 0, 2, 0), /* ctl -- cold: epoch 0, hand 0 */ + opd((uint32_t)RAD_U8, blocks, bbytes), /* host -- the layer's mirror, a block a row */ + opd((uint32_t)RAD_U8, slots, bbytes), /* kv_cache -- the layer's ring, a block a row */ + }; + R4D_PICK(l); +} + /* The QSA block score. The block-key store's height is the KV pool's page count, which the * runtime decides, so `blocks` gives the widest a table entry can address: a bound, not the plan. * Table entries are page ids. */ diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index d5c0ccd4..932ac33a 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -565,6 +565,126 @@ int ref_kv_store(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ kv_store_streamed */ +/* The store of a streamed group: the host mirror is the truth, the device pool is a cache of it. + * + * A streamed group's ring is `slots` blocks deep while the block-id space is `blocks`, and a block + * may be absent from it. This op is `kv_store` with the two copies the group keeps: + * + * host[b] is written ALWAYS, at the block's identity row, whatever the map says; + * kv_cache[res[b]] is written only when `res[b] >= 0`, i.e. the block is resident now. + * + * The residency test belongs in the writer rather than in the resolve, and this is the case that + * decides it: at decode the block this step's tokens land in is the block the last step already + * made resident (a block is `ratio` tokens of one sequence), so a writer that only wrote the + * mirror would leave the ring holding that block's first tokens and every later token missing - + * and the resolve, seeing the block resident, would not copy it. Writing the ring when resident + * and the mirror always means a host block is never stale and a slot never holds a block the + * mirror disagrees with, which is the property the resolve's copy relies on. + * + * The order the caller must keep is store, then resolve, then attention (arch/common/ + * rad_block_attn_gated_fp8.h): the block the current step writes may be absent from the ring, and + * the resolve then copies whole blocks out of the mirror, so it must see this step's bytes. + * + * The two planes are the same bytes in the same paged layout + * (`[notional block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot), so one conversion + * writes both: the mirror is described as an E4M3 plane over the same row pitch and the loop + * stores into `host` and, when resident, `kv_cache`. + * + * `res` is read, not written: residency is the resolve's decision (libref/ref_kvstream.cpp). A + * `res` entry outside [-1, slots) for a block this call touches, or a slot naming a block past the + * id space, is a state fault and is refused before anything is written. */ +int ref_kv_store_streamed(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3]; + const RadTensor *res = &a->t[4], *host = &a->t[5]; + + const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0); + const int64_t block_size = p_int(a, "block_size", 0); + const int64_t kv_heads = p_int(a, "n_head_kv", 0); + if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE; + if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE; + if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE; + if (host->dtype != RAD_U8) return RAD_E_DTYPE; + /* E4M3 (the fp8 QSA family) or bf16 (the default cache dtype). Streaming is dtype-agnostic + * beyond the writer: both planes are byte planes of the same paged layout whose pitch is one + * block, so a bf16 group doubles every offset and stores the value itself, as kv_store_bf16 + * does. A packed fp8_v4/k6_v4 group has no streamed row and is refused. */ + const bool fp8 = kv->dtype == RAD_F8E4M3; + if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED; + if (kv->rank != 4) return RAD_E_SHAPE; + if (kv->shape[1] != kv_heads || kv->shape[2] != block_size || + kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE; + if (host->rank != 2) return RAD_E_SHAPE; + + /* One block of one layer. Both planes are dense rows of it: a padded mirror row would copy a + * block's bytes over its neighbour's, and the two copies must address the same offsets. */ + const int64_t EB = fp8 ? 1 : 2; + const int64_t row = kv_heads * block_size * 2 * head_dim * EB; + const int64_t slots = kv->shape[0], blocks = host->shape[0]; + if (host->shape[1] != row || host->stride[0] * rad_dtype_bytes(host->dtype, 1) != row) + return RAD_E_STRIDE; + if (kv->stride[0] * rad_dtype_bytes(kv->dtype, 1) != row) return RAD_E_STRIDE; + if (slots <= 0 || blocks <= 0) return RAD_E_SHAPE; + if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE; + + const int64_t M = numel(sm); + if (M <= 0 || numel(k) < M * kv_heads * head_dim || numel(v) < M * kv_heads * head_dim) + return RAD_E_SHAPE; + + const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1; + const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds; + const int64_t k_rs = row_stride(k, kv_heads * head_dim); + const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1; + const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds; + const int64_t v_rs = row_stride(v, kv_heads * head_dim); + /* kv_store_bf16 stores the value itself; only the E4M3 row divides by the reader's descales. */ + const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f; + const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f; + + /* Everything that can refuse is checked before the first write: a half-written mirror would + * make the next step's copies plausible and wrong. */ + const int32_t* const R = (int32_t*)res->data; + for (int64_t t = 0; t < M; ++t) { + const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t)); + if (s < 0) continue; /* padded row, no cache slot */ + const int64_t blk = s / block_size; + if (blk >= blocks) return RAD_E_SHAPE; + if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL; + } + + /* The mirror, seen as the plane it holds (E4M3 or bf16): same bytes, same writer, so the two + * copies cannot round differently. */ + RadTensor hkv = *host; + hkv.dtype = kv->dtype; + const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads); + const KVView hv = kv_view(&hkv, head_dim, block_size, kv_heads); + + REF_PAR_FOR(M * kv_heads * head_dim * 2) + for (int64_t t = 0; t < M; ++t) { + const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t)); + if (s < 0) continue; + const int64_t blk = s / block_size, off = s % block_size; + const int64_t hb = blk * hv.sb + off * hv.so; + /* A resident block keeps its slot current; a non-resident one is written to the mirror + * alone and the resolve copies the whole block in when it selects it. */ + const int64_t cb = R[blk] >= 0 ? R[blk] * kvv.sb + off * kvv.so : -1; + for (int64_t h = 0; h < kv_heads; ++h) { + for (int64_t d = 0; d < head_dim; ++d) { + const float xk = ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks; + const float xv = ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs; + stt(&hkv, hb + h * hv.sh + d * hv.sd, xk); + stt(&hkv, hb + h * hv.sh + (head_dim + d) * hv.sd, xv); + if (cb >= 0) { + stt(kv, cb + h * kvv.sh + d * kvv.sd, xk); + stt(kv, cb + h * kvv.sh + (head_dim + d) * kvv.sd, xv); + } + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ rope */ namespace { diff --git a/libref/ref_kvstream.cpp b/libref/ref_kvstream.cpp new file mode 100644 index 00000000..ef122f2b --- /dev/null +++ b/libref/ref_kvstream.cpp @@ -0,0 +1,453 @@ +/* ref_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and + * the ring slots its device pool actually holds (docs/KV-STREAMING.md §3.4 and §4.3, docs/OPS.md + * "Sparse attention (QSA)"). + * + * ============================== What it sits between ============================== + * + * `qsa_select` already dereferences the attention group's block table: it writes + * `sel[q][i] = tb[b]`, the group's POOL PAGE ID (`r4d_qsa_select_bf16.hip:254`, `:686`), and + * `attn_paged` uses each entry as a raw pool page index with no indirection + * (`r4d_attn_decode_h256_gqa6.hip:268`, `:322`; `r4d_attn_paged_gqa8.hip`). When the group's KV + * streams, the device pool is `slots` blocks deep and the block-id space is `blocks`, so a block id + * is no longer an address: `blk * kv_block_stride` would walk out of the layer and silently read + * another layer's bytes. `kv_resolve` turns every selected block id into the ring slot holding it, + * copies the block in from the pinned host mirror when it is not resident, and rewrites `sel` in + * place. Nothing below the rewrite changes: `sel` is the only place the sparse path names KV + * storage, so `attn_paged` reads a resolved table exactly as it reads a fully resident one. + * + * `nsel` and `seqused` stay what `qsa_select` wrote them: the attention's length over the table is + * a token count inside the blocks, not an address, so the rewrite leaves both alone. + * + * ============================== The operands, exactly ============================== + * + * # name role dtype shape what it is + * 0 sel inout i32 [M, sel_pitch] block ids in, ring slots out + * 1 nsel in i32 [M] valid entries of each row + * 2 res inout i32 [blocks] block -> slot, or -1; -2 in flight + * 3 slot_block inout i32 [slots] slot -> block, or -1 free + * 4 slot_state inout i32 [slots, 2] [s,0] epoch of last use, [s,1] heat + * 5 ctl inout i32 [16] the control block (below) + * 6 host in u8 [blocks, block_bytes] the layer's host mirror, identity layout + * 7 kv_cache inout bytes [slots, block_bytes] the layer's ring, as RAD_KV(group, layer) + * + * Order follows the read order of the algorithm, with the cache last as in `kv_store`. `sel` and + * `nsel` keep `qsa_select`'s positions 5 and 6 relative to each other, so the pair reads the same + * way in both ops. + * + * **The miss list is not an operand.** It is a per-call temporary, and a temporary is the row's + * scratch in this codebase (`qsa_select`'s split workspace, docs/OPS.md "qsa_select"): an operand + * would enter the arena planner, the recorded pass's ranges and the tape key for bytes nothing + * outside one launch reads. A device row that needs one declares + * `(next_pow2(slots) + slots) * 4` bytes through `RadKernelInfo::scratch`, laid out + * `int32 miss_block[next_pow2(slots)]` -- the ascending miss list, padded because a launch too wide + * for the kernel's shared claim list sorts it here -- then `int32 miss_slot[slots]`; this reference + * sorts locally and needs none. + * + * ============================== The parameters ============================== + * + * M query rows to resolve; ranged, since a prefill chunk and a decode step differ + * blocks the group's logical block count (the id space, `res`'s extent) + * slots the ring depth (the device pool's extent, `slot_block`'s extent) + * sel_pitch the selection's row pitch in entries (topk + 1); also the bound `nsel` may not pass + * block_bytes bytes one block of ONE layer occupies: the host mirror's row pitch, the pool's slot + * pitch, and the length of every copy + * + * `block_bytes` rather than `block_size` (the block's token count) because the op moves bytes and + * never reads an element: it is the same code at every cache layout (`fp8`, `fp8_v4`, `k6_v4`, + * `bf16`), and it is the number a vectorised copy has to constrain (a block is a whole number of + * 16-byte lanes). It is deliberately NOT a `block_size` key: `Builder::find_kv_consumer` binds a KV + * group to the first unclaimed op after it that carries `block_size`, and the group's block size + * must keep coming off the resolved attention kernel, not off the op that only copies its pages. + * + * `sel_pitch` and `block_bytes` are also pitches the operands carry (`sel.stride[0]`, + * `host.stride[0]`), and this reference requires them to agree: a resolve that read one pitch and + * wrote another would rewrite a row into its neighbour. Stating them in the schema puts them in the + * resolved geometry, where a kernel may constrain them, and in the shape hook, which needs them to + * size `sel` and the two planes. + * + * `slots` is the ring depth, and the OPERAND states it, exactly as `sel`'s extent states `M` and + * its row pitch states `sel_pitch`: `slot_block`'s extent is the ring the call may address and the + * parameter is the ceiling the caller declared. Declare cannot know the ring -- the pool is planned + * after the program is built, and a plugin sees only the context bound -- so the declared `slots` is + * the context and a ring the engine sized smaller (--kv-resident) arrives as a shorter + * operand. A call may never address more than the declaration: `slots > slots_declared` is refused. + * + * ============================== The control block ============================== + * + * `ctl` is 16 int32s, the same [0..9] layout the reference design uses + * (`Strata-main/include/strata/kernels/kv_stream.hpp:78`), 8-byte aligned so the counters can be + * read as u64: + * + * [0] epoch the value the last call used (0 in a fresh block, so the first call is 1) + * [1] hand the CLOCK hand, in [0, slots) + * [2] misses blocks placed by the last call + * [3] overflow 1 once a call could not place every miss; latched, never cleared here + * [4..5] u64 misses every block ever placed + * [6..7] u64 lookups every selection entry ever resolved + * [8..9] u64 calls + * [10] maximum union the largest number of DISTINCT blocks one call has selected + * (hits + misses), so a ring's depth can be sized from measurement + * [11] maximum misses the largest number of blocks one call has placed + * [12] maximum claims the largest number of DISTINCT absent blocks one call has claimed: the + * length of the sorted miss list, so it is what a claim-list capacity has + * to hold. One call's claims are bounded by its lookups, `sum_q nsel[q] <= + * M * sel_pitch` (every claim is a selection entry), and the engine's + * worst case is `max_seqs * sel_pitch`; a device kernel sizes its list from + * those operands rather than a constant (libr4d/r4d_kv_resolve.hip), and + * this is the counter that says whether it did. + * [13..15] zero, reserved + * + * `res`, `slot_block` and `slot_state` are state as well, and the caller brings them up: `res` and + * `slot_block` FILLED WITH -1, `slot_state` and `ctl` ZEROED (one `fill` each, or the group's + * bring-up). That is the reset: there is no separate reset op, because a residency map is fixed at + * bring-up and lives as long as the pool does. Entering a call with any `res` entry of -2, a + * `slot_block` outside [-1, blocks), a `res` outside [-1, slots) or a hand outside [0, slots) is a + * state fault and is refused rather than guessed at. The epoch is a wrap-around i32 counter, only + * ever compared for equality; it would take 2^31 calls - over two years of decoding - for a stale + * stamp to read as a fresh one, and `slot_state[s,1]` would still be the sweep's second chance. + * + * `slot_state[s,1]` is a **two-bit heat counter in [0, 3]** inside an i32 (31 bits unused, so the + * policy needs no new field, no extra per-slot memory and no ABI change). It is bumped by one, and + * clamped at 3, on every use of the slot -- a hit or a placement -- once a slot a call, and halved + * when the sweep passes the slot. Zeroed at bring-up and written nowhere else, so a fresh ring + * starts cold and a negative value is not reachable from a legal state; a reader treats it as cold + * rather than letting a fault strand the sweep. + * + * ============================== The semantics, in order ============================== + * + * 1. **epoch bump.** epoch = ctl[0] + 1. + * 2. **one lookup per distinct block.** For row q ascending, then entry i ascending, over + * i in [0, nsel[q]) (entries at or past nsel[q] are `qsa_select`'s -1 padding and are not + * touched): b = sel[q][i]. + * res[b] >= 0 -> a hit: slot_state[res[b],0] = epoch and, the first time this call stamps + * that slot, slot_state[res[b],1] = min(old + 1, 3). One bump a SLOT a + * call, not one an entry: a block twenty rows name gains one step of heat, + * the same as one a single row names, so the counter measures the calls + * that wanted the block and not the width of the selection. + * res[b] == -1 -> a miss, claimed once: res[b] = -2 and b appended to the miss list. + * res[b] == -2 -> already claimed by an earlier entry; nothing. This is what makes the pass + * one lookup per block without a second structure: the map is its own set. + * 3. **the miss list is ascending block id.** Not first-appearance order: a block claimed by row 3 + * must not evict a different slot from a block claimed by row 0 depending on which thread got + * there first, or two implementations of one contract would place the same blocks in different + * slots and `sel` would differ. Ascending is a fact about the claim set, not about the map, so + * a device implementation orders the claim list itself (a sort of at most `M * sel_pitch` ids); + * nothing here needs a pass over `blocks`, which is the id space and not the call's size. + * 4. **one victim per miss, in that order: identity, a free slot, then a CLOCK (second chance) + * sweep.** For each missed b in ascending order, if `b < slots` and slot b is available -- + * `slot_state[b,0] != epoch` and `slot_block[b]` is either -1 or b itself -- the victim is slot + * b, and the hand does not move. This is a placement preference only: it takes a slot only when + * that slot is free, so it can never evict, and leaving the hand alone means a miss it cannot + * place falls through to exactly the walk below, from exactly the hand it would have seen. Two + * things make it worth having: it maps a block's id to its own slot while the context is + * shorter than the ring, and adjacent block ids then sit in adjacent slots of one layer's + * stripe, which is the order the attention's gather reads them in. Otherwise, visit slots from + * the hand, one at a time, wrapping. A FREE slot -- slot_block[s] == -1 -- is taken before any + * resident block is considered: evicting costs a copy on the next call and a free slot costs + * nothing, so the ring fills its empty region first. A slot with slot_state[s,0] == epoch was + * claimed or hit by this call and is passed, free or not, and keeps its heat counter; this is + * the "never take a slot this call itself uses" rule. When a whole turn finds no free slot, the + * same walk is the CLOCK sweep, with the two-bit heat counter in place of the one-bit + * reference: + * - a slot holding a block whose counter is non-zero: halve it (old >> 1) and pass it. A + * saturated 3 survives exactly two passes (3 -> 1 -> 0), a freshly used 1 exactly one, + * and a slot nothing has wanted for two sweeps is the victim on the next visit. + * - otherwise (a block, counter 0): take it. + * The hand still PICKS the victim -- this is a per-visit decision, not a search -- so the + * policy needs no reduction, no barrier and no extra traffic: an add-and-clamp where a + * constant store was, and a shift where a zero was. That is the whole reason it is affordable + * where an exact LRU is not: the epoch-ordered minimum costs a collective reduction per miss. + * The hand advances one slot per visit, so it ends just past the last slot taken. How many + * slots are free is counted before the sweep; a placement into a free slot makes it live and an + * eviction re-points a live one, so the count only falls to zero and a full ring goes straight + * to CLOCK. The free + * scan is side-effect free when it finds nothing -- it halves no counter and leaves the hand + * where it started -- so a full ring's victim is the sweep's alone. A free slot is taken + * without regard to its stale counter. The CLOCK sweep may + * visit at most 3 * slots slots; every write clamps the counter to 3, so two passes halve any + * value to 0 (docs/KV-STREAMING.md §3.4) and the third places the miss. + * 5. **re-point both maps** as each victim is taken: if the slot held block `old`, res[old] = -1; + * slot_block[s] = b, slot_state[s] = {epoch, min(old + 1, 3)}, res[b] = s. A placement is a + * use, so it carries the same bump a hit does; the victim's counter is 0 by construction (the + * sweep only takes a cold slot), so this is 1 in the common case, and the `min` is what keeps + * the two-bit range true for a slot taken by identity or from the free region. + * 6. **copy**: for each placed (b, s), block_bytes from host[b] into the pool's slot s. A copy is + * a byte copy; nothing is converted, so a streamed block is bit-identical to the block the + * writer put in the mirror. + * 7. **rewrite**: for every entry in [0, nsel[q]), sel[q][i] = res[b] when that is >= 0. Entries + * at or past nsel[q] keep their -1. + * + * `ctl[2] = placed`, `ctl[0] = epoch`, `ctl[1] = hand`, and the counters grow by `placed`, the + * number of entries read (one a lookup, as phase 2 defines a lookup: per entry, not per distinct + * block) and one. The three maxima are the sizes this op exists to measure: `ctl[10]` is the + * largest union one call has selected -- the number a ring must hold -- `ctl[11]` the largest number + * of blocks one call has placed, i.e. how much of that union was not already resident, and + * `ctl[12]` the largest number of claims one call has made, which is the depth the miss list had to + * hold. + * + * ============================== Overflow ============================== + * + * The ring must hold every DISTINCT block one call selects: a hit holds a slot and a miss needs + * another, so the condition is `hits + misses <= slots`. What that union is depends on the launch: + * at decode it is at most `max_seqs * (sel_pitch - 1)`, while above `qsa_exact_to` prefill issues a + * row per query and a launch's union can be a chunk's worth of the history, which is why the engine + * measures it (ctl[10]) instead of assuming a bound. + * + * It is not silent when it does: a miss left unplaced by the sweep reverts to `res[b] = -1`, and + * `ctl[3]` is latched to 1 with `ctl[2]` counting only what was placed. The selection rewrite then + * writes SLOT 0 for every entry whose block is not resident -- a safe address inside the ring, not + * the block's slot. The entry cannot be left holding the block id: on device that value is an + * address past the ring which `attn_paged` dereferences without a bounds check, so a step whose + * resolve overflowed would fault or read another layer's bytes. Slot 0 is defined memory holding a + * real block's KV, so the step produces wrong numbers rather than a fault -- and a caller that finds + * `ctl[3]` set must DISCARD the step, which is the only reading that keeps the engine honest: it + * never serves output computed against a table whose entries do not name their blocks. + * + * ============================== Statefulness ============================== + * + * The op keeps state across calls - the epoch, the hand, the heat counters and its counters - so it + * is not concurrent: two of its launches must never overlap, and the engine must not reorder one + * against another. That is the `rad_kernel_concurrent` promise (`abi/rad_abi.h:493`), which is + * given per row; a plugin's row list lives beside it, and libr4d's is the `kStateful[]` prefix + * table inside `rad_kernel_concurrent` (`libr4d/r4d_rows.cpp:8748-8770`, "A new row with + * stream-ordered state belongs in the list above"). Both kernel rows for this op therefore stay + * out of that list. The absence of the promise is always safe: without it the engine orders the + * launch behind everything before it, which is exactly what the map needs. + * + * Being stateful is not the same as being unrecordable. The op is a pure function of + * device-resident state whose addresses and pitches never change after bring-up (the maps, the + * ring and the mirror are fixed-size from the group's declaration), so a recorded pass replays it + * correctly; rewriting contents is fine, changing a pitch would force a re-record (docs/ + * KV-STREAMING.md §3.4, core/runtime/ctx.cpp's pass key). + * + * ============================== Why this file is the oracle ============================== + * + * It is the obvious serial form of the contract above: one pass over the entries, one sorted miss + * list, one second-chance walk of the slots, one memcpy per miss, one rewrite. Two device + * implementations compared against it must agree on which slot every block lands in, which is the + * part a fast parallel sweep could get right on hits and wrong on victims. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include +#include + +using namespace ref; + +namespace { + +/* The heat counter's two writes, the same function in all three implementations: a use bumps by + * one and saturates at 3, a sweep pass halves, and a negative value (never written by a legal call) + * reads as cold rather than letting it survive every pass. */ +int32_t heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); } +int32_t heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; } + +/* `ctl`'s size, and the index of its first counter (three u64s from [4]). */ +enum { kKvCtlInts = 16, kKvCtlMisses = 4, kKvCtlLookups = 6, kKvCtlCalls = 8 }; +static_assert(kKvCtlLookups == kKvCtlMisses + 2 && kKvCtlCalls == kKvCtlMisses + 4, + "the three counters are consecutive u64s from ctl[4]"); + +/* The byte pitch of a rank-2-or-deeper operand's rows, and whether its trailing extents fill + * exactly `bytes` densely. Both the mirror and the pool are one block a row; a padded row would + * copy a block's bytes over its neighbour's. */ +int64_t row_bytes(const RadTensor* t, int64_t* dense) { + int64_t acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) acc *= t->shape[i]; + *dense = acc; + return t->stride[0] * rad_dtype_bytes(t->dtype, 1); +} + +} /* namespace */ + +int ref_kv_resolve(const RadArgs* a, RadStream) { + if (!have(a, 8)) return RAD_E_INVAL; + const RadTensor *sel = &a->t[0], *nsel = &a->t[1], *res = &a->t[2], *sblk = &a->t[3]; + const RadTensor *sst = &a->t[4], *ctl = &a->t[5], *host = &a->t[6], *pool = &a->t[7]; + const int64_t M = p_int(a, "M", 0), blocks = p_int(a, "blocks", 0); + const int64_t slots_decl = p_int(a, "slots", 0), pitch = p_int(a, "sel_pitch", 0); + const int64_t bbytes = p_int(a, "block_bytes", 0); + /* Zero rows is not a call (docs/OPS.md). */ + if (M <= 0) return RAD_E_SHAPE; + if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE; + + /* The map and the counts are one format, written by one op and read by the writer and the + * sweep: i32, dense. */ + const RadTensor* state[] = { sel, nsel, res, sblk, sst, ctl }; + for (const RadTensor* t : state) + if (t->dtype != RAD_I32) return RAD_E_DTYPE; + if (sel->rank != 2 || sst->rank != 2) return RAD_E_SHAPE; + if (sel->shape[0] < M || sel->shape[1] < pitch) return RAD_E_SHAPE; + if (sel->stride[1] != 1 || sel->stride[0] != pitch) return RAD_E_STRIDE; + if (numel(nsel) < M || nsel->stride[0] != 1) return RAD_E_SHAPE; + if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE; + /* The operand states the ring; the parameter is the ceiling it may not pass (see "The + * parameters"). */ + const int64_t slots = numel(sblk); + if (slots < 1 || slots > slots_decl || sblk->stride[0] != 1) return RAD_E_SHAPE; + if (sst->shape[0] < slots || sst->stride[1] != 1 || sst->stride[0] < 2) return RAD_E_STRIDE; + if (numel(ctl) < kKvCtlInts || ctl->stride[0] != 1) return RAD_E_SHAPE; + if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE; + if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE; + + /* One block of one layer: the mirror's row and the pool's slot are the same bytes, and the + * copy length `block_bytes` is both pitches. */ + int64_t hdense = 0, pdense = 0; + if (row_bytes(host, &hdense) != bbytes || hdense * rad_dtype_bytes(host->dtype, 1) != bbytes) + return RAD_E_STRIDE; + if (row_bytes(pool, &pdense) != bbytes || pdense * rad_dtype_bytes(pool->dtype, 1) != bbytes) + return RAD_E_STRIDE; + + int32_t* const R = (int32_t*)res->data; + int32_t* const SB = (int32_t*)sblk->data; + int32_t* const ST = (int32_t*)sst->data; + int32_t* const C = (int32_t*)ctl->data; + const int64_t stp = sst->stride[0]; + /* The counters are read and written as u64 in an i32 block. */ + if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE; + + /* ---- everything that can refuse, before anything is written; the selection is read once and + * kept, so phase 7 writes values it did not have to re-read ---- */ + std::vector off, ent; + for (int64_t q = 0; q < M; ++q) { + const int64_t n = ld_int(nsel->dtype, nsel->data, q); + if (n < 0 || n > pitch) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t b = ld_int(sel->dtype, sel->data, q * pitch + i); + if (b < 0 || b >= blocks) return RAD_E_INVAL; + off.push_back(q * pitch + i); + ent.push_back(b); + } + } + for (int64_t b = 0; b < blocks; ++b) + if (R[b] < -1 || R[b] >= slots) return RAD_E_INVAL; /* -2 is never left by a call */ + for (int64_t s = 0; s < slots; ++s) + if (SB[s] < -1 || SB[s] >= blocks) return RAD_E_INVAL; + if (C[1] < 0 || C[1] >= slots) return RAD_E_INVAL; + + /* ---- 1. the epoch ---- */ + const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u); + + /* ---- 2. hits, and one claim per distinct miss (the map is its own set) ---- */ + std::vector miss; + for (size_t e = 0; e < ent.size(); ++e) { + const int32_t b = (int32_t)ent[e]; + const int32_t s = R[b]; + if (s >= 0) { + /* One bump a slot a call (see "The semantics", step 2). */ + if (ST[s * stp] != epoch) { + ST[s * stp] = epoch; + ST[s * stp + 1] = heat_up(ST[s * stp + 1]); + } + } else if (s == -1) { + R[b] = -2; + miss.push_back(b); + } + } + const int64_t lookups = (int64_t)ent.size(); + + /* ---- 3. the canonical miss order ---- */ + std::sort(miss.begin(), miss.end()); + + /* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot + * this call uses ---- */ + /* Identity first (see "The semantics", step 4): a missed block whose id fits the ring and whose + * own slot is free takes that slot and leaves the hand alone, so the fallback below runs from + * the hand it would always have run from. A free slot is not a victim (see step 4): the ring's + * empty region fills before any resident block is evicted. The free scan halves no counter + * and does not move the hand when it finds nothing, so a full ring takes the CLOCK victim it + * always took. The count below is what lets a full ring go straight to CLOCK: no placement + * frees a slot and no eviction does either, so a count of zero holds for the rest of the call. */ + int64_t free_left = 0; + for (int64_t s = 0; s < slots; ++s) + if (SB[s] < 0 && ST[s * stp] != epoch) ++free_left; + int64_t hand = C[1]; + int64_t placed = 0; + bool overflow = false; + for (size_t k = 0; k < miss.size(); ++k) { + const int32_t b = miss[k]; + int64_t victim = -1; + if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b)) + victim = b; + if (victim < 0 && free_left > 0) { + int64_t h = hand; + for (int64_t scanned = 0; scanned < slots; ++scanned) { + const int64_t s = h; + h = h + 1 == slots ? 0 : h + 1; + if (ST[s * stp] == epoch) continue; /* used by this call */ + if (SB[s] >= 0) continue; /* holds a block */ + victim = s; + hand = h; + break; + } + if (victim < 0) free_left = 0; + } + if (victim < 0) { + for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) { + const int64_t s = hand; + hand = hand + 1 == slots ? 0 : hand + 1; + if (ST[s * stp] == epoch) continue; /* used by this call */ + if (SB[s] >= 0 && ST[s * stp + 1] > 0) { /* second chance */ + ST[s * stp + 1] = heat_down(ST[s * stp + 1]); + continue; + } + victim = s; + break; + } + } + if (victim < 0) { overflow = true; break; } + /* ---- 5. re-point both maps ---- */ + if (SB[victim] < 0 && free_left > 0) --free_left; /* a free slot just filled */ + if (SB[victim] >= 0) R[SB[victim]] = -1; + SB[victim] = b; + ST[victim * stp] = epoch; + ST[victim * stp + 1] = heat_up(ST[victim * stp + 1]); + R[b] = (int32_t)victim; + ++placed; + } + /* A miss the sweep could not place is not resident: undo the claim, so the next call may claim + * it again, and leave its selection entries naming the block (see "Overflow"). */ + for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1; + + /* ---- 6. the copies, one block each, in miss order ---- */ + const uint8_t* const hb = (const uint8_t*)host->data; + uint8_t* const pb = (uint8_t*)pool->data; + for (int64_t k = 0; k < placed; ++k) { + const int32_t b = miss[(size_t)k]; + std::memcpy(pb + (int64_t)R[b] * bbytes, hb + (int64_t)b * bbytes, (size_t)bbytes); + } + + /* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */ + for (size_t e = 0; e < ent.size(); ++e) { + const int32_t s = R[ent[e]]; + /* An entry of a miss the sweep could not place names slot 0, not its block id: the id is + * an address outside the ring (see "Overflow"). ctl[3] is what says the table is unusable. */ + st_int(sel->dtype, sel->data, off[e], s >= 0 ? s : 0); + } + + /* ---- the bookkeeping ---- */ + /* The union is over DISTINCT blocks, so it is counted from the slots this call stamped (every + * block it hit or placed leaves the call's epoch there) plus the misses it could not place: + * entries repeat, a selection names one block per row and many rows share swaths of history. */ + int64_t used = 0; + for (int64_t s = 0; s < slots; ++s) + if (ST[s * stp] == epoch) ++used; + const int64_t uni = used + (int64_t)miss.size() - placed; + C[0] = epoch; + C[1] = (int32_t)hand; + C[2] = (int32_t)placed; + if (overflow) C[3] = 1; + /* The sizes the counters report: the union this call selected and the part of it that had to + * be copied in. + * A ring sized for the largest union a launch selects is the whole answer to "how large does the + * ring have to be" (docs/KV-STREAMING.md §3.4). */ + if (uni > C[10]) C[10] = (int32_t)uni; + if (placed > C[11]) C[11] = (int32_t)placed; + if ((int64_t)miss.size() > C[12]) C[12] = (int32_t)miss.size(); + uint64_t* const ctr = (uint64_t*)(C + kKvCtlMisses); + ctr[0] += (uint64_t)placed; + ctr[1] += (uint64_t)lookups; + ctr[2] += 1u; + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index b652f7d1..ccf6f1d2 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -153,6 +153,8 @@ int ref_chan_stats (const RadArgs*, RadStream); /* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */ int ref_sam_attn (const RadArgs*, RadStream); int ref_kv_store (const RadArgs*, RadStream); +/* the store of a streamed group: the host mirror always, the ring slot when the block is resident */ +int ref_kv_store_streamed (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); int ref_qk_norm_rope (const RadArgs*, RadStream); @@ -242,6 +244,8 @@ int ref_qsa_score (const RadArgs*, RadStream); int ref_qsa_select (const RadArgs*, RadStream); int ref_qsa_tail_store (const RadArgs*, RadStream); int ref_qsa_work (const RadArgs*, RadStream); +/* the residency map between a streamed group's block ids and its ring slots (ref_kvstream.cpp) */ +int ref_kv_resolve (const RadArgs*, RadStream); int ref_dflash_conv (const RadArgs*, RadStream); /* ---- mixture of experts */ @@ -406,6 +410,7 @@ REF_SHAPE_FN(ref_mix_rows); REF_SHAPE_FN(ref_chan_stats); REF_SHAPE_FN(ref_sam_attn); REF_SHAPE_FN(ref_kv_store); +REF_SHAPE_FN(ref_kv_store_streamed); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); REF_SHAPE_FN(ref_qk_norm_rope); @@ -487,6 +492,7 @@ REF_SHAPE_FN(ref_qsa_score); REF_SHAPE_FN(ref_qsa_select); REF_SHAPE_FN(ref_qsa_tail_store); REF_SHAPE_FN(ref_qsa_work); +REF_SHAPE_FN(ref_kv_resolve); REF_SHAPE_FN(ref_dflash_conv); REF_SHAPE_FN(ref_router_topk); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 7d9ed170..07c7db77 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -403,6 +403,17 @@ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n P_F64O("k_scale"), P_F64O("v_scale") }; static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping"), INOUT("kv_cache") }; +/* The streamed store, `kv_store` with the group's two copies: `host` is the authoritative mirror + * (always written) and `res` is the residency map that says whether the block is in the ring. The + * parameters are kv_store's, because the layout and the conversion are the same; `res` is read, + * never written, since residency is `kv_resolve`'s decision. */ +static const RadParamSpec pKvStoreStreamed[] = { + P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"), + P_F64O("k_scale"), P_F64O("v_scale") +}; +static const RadOperandSpec oKvStoreStreamed[] = { OPD("k"), OPD("v"), OPD("slot_mapping"), + INOUT("kv_cache"), OPD("res"), + INOUT("host") }; static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), @@ -457,6 +468,17 @@ static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), static const RadOperandSpec oQsaWork[] = { OPD("k"), OPD("pos"), OPD("cu"), OPD("state"), OPD("sidx"), OPD("bt"), OPD_O("rope"), OUT("stage"), OUT("page"), OUT("bpos"), OUT("nc") }; +/* The residency map of a streamed group (ref_kvstream.cpp, docs/KV-STREAMING.md §3.4). No + * `block_size`: the op moves whole blocks by the byte and never reads an element, and a + * `block_size` key would make it a KV group's consumer, taking the binding away from the resolved + * attention kernel (Builder::find_kv_consumer). `sel_pitch` and `block_bytes` are the selection's + * row pitch and one block of one layer's byte extent. The miss list is the row's scratch, not an + * operand. */ +static const RadParamSpec pKvResolve[] = { P_INT("M"), P_INT("blocks"), P_INT("slots"), + P_INT("sel_pitch"), P_INT("block_bytes") }; +static const RadOperandSpec oKvResolve[] = { INOUT("sel"), OPD("nsel"), INOUT("res"), + INOUT("slot_block"), INOUT("slot_state"), + INOUT("ctl"), OPD("host"), INOUT("kv_cache") }; /* DFlash2's grouped convolution, libr4d's schema exactly. */ static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"), @@ -1383,6 +1405,11 @@ static const RadOpSchema kSchemas[] = { { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, +{ "kv_store_streamed", ARR(pKvStoreStreamed), ARR(oKvStoreStreamed), + "kv_store for a streamed group: writes the token's k and v into the group's host mirror ALWAYS, " + "at the block's identity row, and into the ring slot only when the residency map says the block " + "is resident. A negative slot is skipped. The mirror is the truth; a block absent from the ring " + "is copied in whole by kv_resolve." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: " "rot values a row, cos for the first half and sin for the second. The angles are `rope`'s " @@ -1409,6 +1436,15 @@ static const RadOpSchema kSchemas[] = { "The blocks completing in this batch: per block its `ratio` raw keys (this step's rows, or the " "tail's at q % ring) staged contiguously, its block-key page and its first-token position; slots " "past the count get page -1. nc is each sequence's complete-block count." }, +{ "kv_resolve", ARR(pKvResolve), ARR(oKvResolve), + "Makes every block the selections name resident and rewrites them as ring slots: an epoch bump, " + "a hit or a single claim per distinct block, a free slot before any resident one and otherwise " + "one CLOCK (second-chance) victim per miss - never a slot this call uses - the two maps " + "re-pointed, each missed block copied from the host mirror " + "into its slot, then every valid sel entry replaced by the slot holding its block. nsel, and so " + "the attention's length, are unchanged. The ring must hold the call's distinct blocks; a call " + "that cannot place every miss latches ctl[3] and leaves those entries naming blocks, never a " + "fabricated slot." }, { "dflash_conv", ARR(pDflashConv), ARR(oDflashConv), "DFlash2's grouped dynamic depthwise convolution: out[t][h] = sum over taps j, j == 0 or " "t % block_size >= j, of (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]." }, @@ -2234,6 +2270,9 @@ SIMPLE("ref_sam_attn", "sam_attn", "attn", ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_kv_store, nullptr), +ROW("ref_kv_store_streamed", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the resident ring slot", DT_ANY, + nullptr, 0, nullptr, nullptr, ref_kv_store_streamed, nullptr), SIMPLE("ref_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, ref_rope), SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding", DT_FLOAT, ref_qk_norm_rope), @@ -2276,6 +2315,9 @@ SIMPLE("ref_qsa_tail_store", "qsa_tail_store", "attn", ref_qsa_tail_store), SIMPLE("ref_qsa_work", "qsa_work", "attn", "QSA work list: completing blocks' keys, pages and positions", DT_FLOAT, ref_qsa_work), +SIMPLE("ref_kv_resolve", "kv_resolve", "attn", + "streamed KV residency map: selected block ids become ring slots, misses copied in", + "i32 maps, u8 block planes", ref_kv_resolve), SIMPLE("ref_dflash_conv", "dflash_conv", "draft", "DFlash2 grouped dynamic depthwise convolution", DT_FLOAT, ref_dflash_conv), SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 9cfc2d9d..a2527135 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1455,6 +1455,36 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("kv_store", operand, out); } +/* The streamed store. Same geometry as `kv_store`, with the mirror and the residency map beside + * the ring: the mirror is one block a row of the same byte pitch. + * + * The described call touches ONE block, resident in ring slot 0. The draw vocabulary cannot express + * an injective residency map (block -> slot is a permutation, and a draw is a free choice per + * entry), and two blocks drawing one slot would make two tokens write the same ring byte -- a race + * the parallel rerun rightly reports. So the generated case exercises the conversion, the positions + * within a block, the mirror write and the resident ring write; a partly resident map and the + * mirror-only step are built by hand in tests/ref_test.cpp and libavx's hand cases. `M <= block_size` + * keeps every token on its own position of that one block. */ +int ref_kv_store_streamed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t kvh = gi(p, n_p, "n_head_kv", 0); + const int64_t bs = gi(p, n_p, "block_size", 0); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); + const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_F8E4M3 : kv; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + + Opd o; + o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* k */ + o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* v */ + o.t_idx({ M }, bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping, one block */ + o.t(KV, { 1, kvh, bs, 2 * hd }); /* kv_cache, INOUT */ + o.t_idx({ 1 }, 1, -1, 0); /* res -- resident in slot 0 */ + o.t((uint32_t)RAD_U8, { 1, row }); /* host, INOUT */ + return o.finish("kv_store_streamed", operand, out); +} + int ref_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -1644,6 +1674,32 @@ int ref_qsa_work_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("qsa_work", operand, out); } +/* The residency map and the two byte planes. `sel` is described as block ids, which is what + * `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch. + * + * A described residency map can only be an all-resident one: the description vocabulary draws an + * index in [0, idx_max) or a non-negative constant, and a cold entry is -1 (`res[b] == -1`, an + * absent block), which no draw expresses. So a tool that calls this op cold sees every block + * resident, which exercises the epoch, the rewrite and the bookkeeping but never a miss, an + * eviction or a copy. The service-shaped cases (a partly resident pool, a second chance, an + * eviction, an overflow) are built by hand in tests/ref_test.cpp and in libavx's hand cases. */ +int ref_kv_resolve_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), blocks = gi(p, n_p, "blocks", 0); + const int64_t slots = gi(p, n_p, "slots", 0), pitch = gi(p, n_p, "sel_pitch", 0); + const int64_t bbytes = gi(p, n_p, "block_bytes", 0); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ M, pitch }, blocks, -1, 0); /* sel -- one block id an entry */ + o.t_idx({ M }, pitch + 1, -1, 0); /* nsel -- 0 .. sel_pitch */ + o.t_idx({ blocks }, slots, -1, 0); /* res -- every block resident, no -2 */ + o.t_idx({ slots }, blocks, -1, 0); /* slot_block -- the reverse map */ + o.t_idx({ slots, 2 }, 2, 0, 0); /* slot_state -- cold: epoch 0, no reference */ + o.t_idx({ 16 }, 2, 0, 0); /* ctl -- cold: epoch 0, hand 0 */ + o.t((uint32_t)RAD_U8, { blocks, bbytes }); /* host -- the layer's mirror, a block a row */ + o.t((uint32_t)RAD_U8, { slots, bbytes }); /* kv_cache -- the layer's ring, a block a row */ + return o.finish("kv_resolve", operand, out); +} + /* `delta` is described as the whole [T, 2 * taps * NG] coefficient projection, of which the op * reads the first taps * NG columns at the row pitch: the form the architecture issues, and the * pitch libr4d requires. */ From f16854499cf5ec7ac3acaae78b286ed9ddcfde12 Mon Sep 17 00:00:00 2001 From: mici81 Date: Thu, 22 Oct 2026 12:25:50 +0000 Subject: [PATCH 06/27] decode launches: gate_up + gated_quant_fp8 folded for MXFP4 (gemm_nt_q_gated_mx) A decode step on Qwen3.8-27B at TP2 issues 631 kernels a card, and a dependent kernel costs the card 3.5-6.4 us in a replayed graph on gfx1201 however little it does, so launches are about 13 % of a step. - gemm_nt_q_gated_mx: gemm_nt_q_gated over an OCP-MXFP4 weight (b_ref after b_scale; a new op, not an optional operand on the old one). Row gemm_mxfp4a8_gated_gemv: M <= 8, a block per 128-column group of the gated output, a wave per gate or up tile running all of the gemv WMMA form's partials in its order, then gated_quant_fp8's epilogue -- byte-identical to gemv + gated_quant_fp8 (selftest, M = 1..8, Qwen's and TranslateGemma's gate_up). The MLP block declares it for a plain MXFP4 gate_up when a loaded library declares the op (libref does not), so a CPU-only engine takes the pair. Layout hooks map its b_ref (operand 4) to gemm_nt_q's index, so the weight is stored once. The fold: 82.5 us against 81 + 4.6 for the pair at Qwen's gate_up, 98.8 against 104 + 4.7 at TranslateGemma's. - --perfmxd times gated_quant_fp8 and the fold beside the gemv row at a gate_up shape. Greedy texts of four prompts, speculation 0 and 3, identical to the production build. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/common/rad_block_mlp_fp8.h | 29 +++-- arch/common/rad_fp8.h | 22 ++++ docs/OPS.md | 5 + libr4d/r4d_fuse.cpp | 39 +++++++ libr4d/r4d_gemm_mxfp4a8_gemv.hip | 190 +++++++++++++++++++++++++++++++ libr4d/r4d_layout.cpp | 19 ++++ libr4d/r4d_plugin.h | 6 + libr4d/r4d_rows.cpp | 41 +++++++ libr4d/r4d_selftest.cpp | 153 +++++++++++++++++++++++++ 9 files changed, 497 insertions(+), 7 deletions(-) diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index e9460530..077e6cfc 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -119,18 +119,27 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, swiglu_limit)); - /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit - * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product. - * Declared over int8 codes, only a host kernel would take it, and that would pin the layer's - * weights to the host. */ - if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx && - !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) + /* The fold: decl_gated_fold, an fp8a8 tile, for block-fp8 weights; decl_gated_fold_mx for a + * plain MXFP4 one at one to eight rows. bf16, f32-scaled, rotated MXFP4, rotated 5-bit, 4-bit + * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product, which + * neither fold computes. Declared over int8 codes, only a host kernel would take it, and that + * would pin the layer's weights to the host. */ + const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale; + if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, { w.h.q, w.h.s }, gq_ffn.want_x ? std::initializer_list{ w.ffn.q, w.ffn.s, w.ffn.x } : std::initializer_list{ w.ffn.q, w.ffn.s }, &gated_rows); + else if (fold_ok && gate_up.mx && !gate_up.paro) + op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, + gate_up.wref, { w.h.q, w.h.s }, + gq_ffn.want_x + ? std::initializer_list{ w.ffn.q, w.ffn.s, + w.ffn.x } + : std::initializer_list{ w.ffn.q, w.ffn.s }, + &gated_rows); RAD_ARCH_TRY(down.declare(b, nm, g, down_base, g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l), { src.down }, w.ffn, w.h.x)); @@ -179,7 +188,13 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const } inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { - if (op_gated && rows <= gated_rows) { + if (op_gated && rows <= gated_rows && gate_up.mx) { + RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), + brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), + RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff), + brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK), + gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE); + } else if (op_gated && rows <= gated_rows) { RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff), diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 4cdbb459..9af9c854 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1692,6 +1692,28 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, return op; } +/* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0 + * plane and that plane again as the per-row reference), declared for M up to min(rows, 8), the band + * of libr4d's one-to-eight-row GEMM it is built on. Optional like decl_gated_fold, and asked for + * only when a loaded library declares the op: libref does not, so a CPU-only engine takes the pair + * without ever naming it. */ +inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight ws, rad_weight wref, + std::initializer_list reads, + std::initializer_list writes, int64_t* gated_rows) { + const int64_t hi = rows < 8 ? rows : 8; + if (hi <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0; + if (!rad_op_declared(b, "gemm_nt_q_gated_mx")) return 0; + const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_STR("act", "silu")), + RAD_WEIGHTS(w, ws, wref)), + reads, writes); + if (op) *gated_rows = hi; + return op; +} + } /* namespace arch */ } /* namespace rad */ diff --git a/docs/OPS.md b/docs/OPS.md index 19db01f8..95840ce5 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -591,6 +591,7 @@ and is optional. | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +| `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? | `quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, `scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an @@ -604,6 +605,10 @@ it does not produce that op's `y`. `act` is required here, unlike on the quantis implementation may compile one gate only, and an optional parameter would let it resolve for another. +`gemm_nt_q_gated_mx` is the same fold over an OCP-MXFP4 weight (`dtype` `mxfp4a8`, `group` 32), which +`gemm_nt_q` reads with the per-row reference exponent `b_ref` after `b_scale`. A schema of its own +because an op's operand count is fixed for the plugins built against it. + `swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 447d76b6..8db942ae 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -510,6 +510,45 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre } } +/* ========================================================================================== + * gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight. + * (row: gemm_mxfp4a8_gated_gemv; kernel: libr4d/r4d_gemm_mxfp4a8_gemv.hip, the gated form) + * + * Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16 + * + * The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the + * weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not + * mirrored. + */ +extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step, + RadFuseStep* out) { + if (!out) return RAD_E_INVAL; + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const char* dt = r4d_pgets(p, n_p, "dtype"); + if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED; + if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED; + if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED; + if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; + + switch (step) { + case 0: { + Step s(out, "gemm_nt_q"); + s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K") + .mirror(p, n_p, "group").mirror(p, n_p, "dtype"); + /* a, a_scale, b, b_scale, y, a_sum, b_ref */ + return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 }); + } + case 1: { + Step s(out, "gated_quant_fp8"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128) + .pstr("dtype", "bf16").mirror(p, n_p, "act"); + return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */ + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue. * (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libr4d/ diff --git a/libr4d/r4d_gemm_mxfp4a8_gemv.hip b/libr4d/r4d_gemm_mxfp4a8_gemv.hip index 0972c411..6c2e738b 100644 --- a/libr4d/r4d_gemm_mxfp4a8_gemv.hip +++ b/libr4d/r4d_gemm_mxfp4a8_gemv.hip @@ -35,9 +35,11 @@ #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_mxfp4.h" +#include "r4d_q8.h" #include #include +#include #include #define R4D_MXG_MAX_M 8 @@ -346,3 +348,191 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) { } return RAD_OK; } + +// ============================================================== the gated form (gemm_nt_q_gated_mx) +// +// The gate_up GEMM with gated_quant_fp8's pass in its epilogue, so the [M, 2n] bf16 product is never +// written and the quantiser is not a launch of its own. One block a 128-column group of the gated +// output (one activation scale group of the down projection's input): sixteen waves, one 16-column +// weight tile each -- the group's eight gate tiles (weight rows 128 g ..) and its eight up tiles (rows +// n + 128 g ..). +// +// Byte-identical to the WMMA form above followed by gated_quant_fp8. A wave runs, for its tile, what +// all R4D_MXG_KW waves of that kernel run: partial v sums chunks v, v + KW, .. in order, and the +// partials are added v = 0, 1, .. from zero, as that kernel's epilogue adds its waves' rows of sP. +// Only one partial is live at a time, which is why the chunks are taken in that order rather than +// in K order. The scaled sum is rounded to bf16 by the same conversion, and from there the arithmetic +// is r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's +// amax, scale amax / 448, codes through q8_pack4. +namespace { +__device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } +__device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf + const uint32_t u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +} // namespace + +template +__global__ __launch_bounds__(16 * 32) +void r4d_gemm_mxfp4a8_gated_kernel( + const unsigned char* __restrict__ A, const float* __restrict__ As, + const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, + const unsigned char* __restrict__ Wref, uint8_t* __restrict__ Q, float* __restrict__ S, + uint16_t* __restrict__ Y, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, + int y_ld) { + constexpr int KW = R4D_MXG_KW; + __shared__ uint16_t sG[16][R4D_MXG_MAX_M][16]; // bf16 gate (waves 0..7) and up (8..15) + const int lane = threadIdx.x & 31; + const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5); + const int nt = (wave >> 3) * (n >> 4) + blockIdx.x * 8 + (wave & 7); // this wave's weight tile + const int col = lane & 15, khalf = lane >> 4; + const int row = col; + const bool live = row < M; + const int ksteps = K >> 4, chunks = K >> 7; + const unsigned* __restrict__ Wp = (const unsigned*)W; + const int ref = (int)Wref[nt * 16 + col]; + mxg_v8f sum = (mxg_v8f)(0.f); + for (int v = 0; v < KW; ++v) { + mxg_v8f tot = (mxg_v8f)(0.f); + for (int ch = v; ch < chunks; ch += KW) { + unsigned wv[8]; +#pragma unroll + for (int s = 0; s < 8; ++s) + wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]); + int e8[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col]; + mxg_v2i af[8]; +#pragma unroll + for (int s = 0; s < 8; ++s) { + if (live) { + const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8); + af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1]; + } else { + af[s][0] = 0; af[s][1] = 0; + } + } + mxg_v8f acc = (mxg_v8f)(0.f); +#pragma unroll + for (int s = 0; s < 8; ++s) { + unsigned lo, hi; + r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi); + mxg_v2i wf; + wf[0] = (int)lo; wf[1] = (int)hi; + acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc); + } + const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f; +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]); + } +#pragma unroll + for (int e = 0; e < 8; ++e) sum[e] += tot[e]; + } + // acc[e] (and so sum[e]): row (lane & 15), column khalf * 8 + e of the tile. + if (live) { +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int c = khalf * 8 + e; + const float rf = __int_as_float((int)Wref[nt * 16 + c] << 23); + const __hip_bfloat16 h = (__hip_bfloat16)(ABLK ? sum[e] * rf : sum[e] * rf * As[(size_t)row * as_rs]); + sG[wave][row][c] = *(const uint16_t*)&h; + } + } + __syncthreads(); + // gated_quant_fp8: one wave a row, a lane four consecutive columns of the group. + if (wave < M) { + const int m = wave, c0 = lane * 4, t = c0 >> 4, cc = c0 & 15; + const size_t gcol = (size_t)blockIdx.x * 128 + c0; + float vq[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float g = mxg_bf2f(sG[t][m][cc + j]); + const float a = g / (1.0f + expf(-g)); + const uint16_t h = mxg_f2bf(a * mxg_bf2f(sG[8 + t][m][cc + j])); + if (Y) Y[(size_t)m * y_ld + gcol + j] = h; + vq[j] = mxg_bf2f(h); + } + float mx = fmaxf(fmaxf(fabsf(vq[0]), fabsf(vq[1])), fmaxf(fabsf(vq[2]), fabsf(vq[3]))); + mx = r4d_wave_max(mx); + const float sc = mx > 0.0f ? mx * (1.0f / q8_top()) : 1.0f; + if (lane == 0) S[(size_t)m * s_ld + blockIdx.x] = sc; + const float inv = 1.0f / sc; + *(uint32_t*)(Q + (size_t)m * q_ld + gcol) = q8_pack4(vq[0], vq[1], vq[2], vq[3], inv); + } +} + +namespace { +void mxgg_launch(bool ablk, const void* a, const void* as, const void* w, const void* ws, + const void* wr, void* q, void* s, void* y, int M, int K, int n, int as_rs, int lda, + int ldws, int q_ld, int s_ld, int y_ld, RadStream stream) { + const dim3 grid((uint32_t)(n / 128)), block(16 * 32); + hipStream_t st = (hipStream_t)stream; + if (ablk) + hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, + (const unsigned char*)a, (const float*)as, (const unsigned char*)w, + (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, + (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld); + else + hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, + (const unsigned char*)a, (const float*)as, (const unsigned char*)w, + (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, + (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld); +} +} // namespace + +/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in + * r4d_rows.cpp): gemm_nt_q_gated's with the per-row reference `b_ref` after `b_scale`. The weight + * is one [N, K] plane, gate rows then up rows, N = 2 * the gated width; no parts. */ +enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6, + MXGG_Y = 7 }; + +extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, MXGG_A); + const RadTensor* xs = r4d_opt(a, MXGG_AS); + const RadTensor* w = r4d_opt(a, MXGG_B); + const RadTensor* ws = r4d_opt(a, MXGG_BS); + const RadTensor* wr = r4d_opt(a, MXGG_BR); + const RadTensor* q = r4d_opt(a, MXGG_Q); + const RadTensor* sc = r4d_opt(a, MXGG_S); + const RadTensor* y = r4d_opt(a, MXGG_Y); + if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL); + if (q->rank != 2 || sc->rank != 2 || x->rank < 2) return R4D_NO(RAD_E_SHAPE); + if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE); + const char* act = r4d_gets(a, "act"); + if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED); + + /* The gated width from `q`, the buffer written; N and K from the op's parameters, since the + * weight operands are packed bytes. */ + const long long M = q->shape[0], nout = q->shape[1]; + const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0); + if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128) return R4D_NO(RAD_E_SHAPE); + if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE); + if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE); + if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE); + if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE); + /* The activation scale per (row, 128 of K), or per row. */ + bool ablk; + long long as_rs; + if (xs->rank == 2 && xs->shape[0] == M && xs->shape[1] == K / 128) { + ablk = true; + as_rs = r4d_row_pitch(xs); + } else if (xs->rank == 1 && xs->shape[0] == M) { + ablk = false; + as_rs = 1; + } else { + return R4D_NO(RAD_E_SHAPE); + } + const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + const long long yp = y ? r4d_row_pitch(y) : 0; + if (lda < 0 || as_rs < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) || + !r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4) + return R4D_NO(RAD_E_ALIGN); + + R4D_TRY("gemm_mxfp4a8_gated", + mxgg_launch(ablk, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data, + y ? y->data : nullptr, (int)M, (int)K, (int)nout, (int)as_rs, (int)lda, (int)N, + (int)qp, (int)sp, (int)yp, s)); + return RAD_OK; +} diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 6ef46f6f..8aa32ff5 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -939,6 +939,25 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand, return RAD_OK; } +/* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its + * `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for + * the reference plane in one form and the loader stores it once. */ +static int mx_gated_operand(int operand) { return operand == 4 ? Q_BREF : operand; } + +extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return r4d_rad_layout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, out); +} + +extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + return r4d_rad_relayout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, dst, + dst_bytes); +} + /* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is * the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b * low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 61da0830..872dbf7b 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -459,6 +459,7 @@ int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream); int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream); +int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream); int r4d_rad_dequant_w4 (const RadArgs*, RadStream); int r4d_rad_rowtopk (const RadArgs*, RadStream); int64_t r4d_rad_rowtopk_scratch(const RadArgs*); @@ -665,6 +666,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, @@ -917,6 +922,7 @@ int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFu int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_gemm_nt_q_gated_mx (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 5e611270..70906ab5 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1627,6 +1627,20 @@ static const RadOperandSpec oGemmNtQGated[] = { { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 }, }; +/* The same fold over an OCP-MXFP4 gate_up weight, which gemm_nt_q reads with a per-row reference + * exponent (`b_ref`) beside its scale plane. A schema of its own rather than an optional operand on + * gemm_nt_q_gated: an op's operand count is part of its contract with the plugins already built + * against it. */ +static const RadOperandSpec oGemmNtQGatedMx[] = { + { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "b_ref", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, +}; /* The gate in a separate operand, as in a gated attention: the gate is a column slice of the * [q|gate] projection and `x` the attention output, two buffers with different pitches. A row is a @@ -3363,6 +3377,10 @@ static const RadOpSchema kSchemas[] = { "columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. " "Byte-identical to the two ops it replaces, which is what makes it substitutable " "rather than a second numerical path."), + SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx, + "gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 " + "(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the " + "epilogue, byte-identical to the two ops it replaces."), SCHEMA("gate_quant_fp8", pGateQuantFp8, oGateQuantFp8, "the same, with the gate in its own operand rather than packed beside x."), SCHEMA("quant_act_fp8", pQuantActFp8, oQuantActFp8, @@ -4808,6 +4826,12 @@ static const RadConstraint cGemmNtQGatedFp8[] = { C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"), }; +/* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block + * per 128-column group of the gated output (N/2 a multiple of 128). */ +static const RadConstraint cGemmNtQGatedMx[] = { + C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"), + C_IN("act", "silu"), +}; static const RadConstraint cGateQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; @@ -7742,6 +7766,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gemv, nullptr, r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 }, +{ "gemm_mxfp4a8_gated_gemv", "gemm_nt_q_gated_mx", "gemm", + "the gemv row's WMMA form over a gate_up weight with gated_quant_fp8's pass in its epilogue: a " + "block per 128-column group of the gated output, a wave per gate or up tile running all of that " + "form's K partials in its order, so the [M, 2n] bf16 product is never written", + "M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column " + "scale group); act silu only; the skinny kernel's fragment-order weight, [K/32][N] E8M0 " + "exponents and per-row reference exponent, gate rows then up rows", + "e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K, and the " + "QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 " + "product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGemmNtQGatedMx), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, nullptr, + r4d_rad_layout_mxfp4_gated, r4d_rad_relayout_mxfp4_gated, nullptr, nullptr, + /* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */ + r4d_fuse_gemm_nt_q_gated_mx }, + { "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm", "the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver " "reduction, the weight unpacked through LDS, streaming weight loads", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 8602d592..39a17c4e 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6073,6 +6073,127 @@ static void w4a8_multi_user_exact(const Plugin& pl) { } } +/* ---- the MXFP4 gated fold, against the pair it replaces ------------------------------------- + * + * gemm_mxfp4a8_gated_gemv (gemm_nt_q_gated_mx) against gemm_mxfp4a8_gemv followed by + * gated_quant_fp8, on the same weight bytes (one relayout, through the gemv row's hooks, which the + * gated row shares) and activation. Codes, scales and the bf16 product must be identical, and the + * codes mostly non-zero (zeroed buffers compare equal). Run twice: with `out_bf16`, and without it, + * where the codes and scales must still match. */ +static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk) { + const char* row = "gemm_mxfp4a8_gated_gemv"; + if (!sel(row)) return; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + gated_quant_fp8, M=%lld N=%lld K=%lld%s", + row, (long long)M, (long long)N, (long long)K, ablk ? " ascale=row x 128" : ""); + const RadKernelInfo* rg = find(pl, row); + const RadKernelInfo* rv = find(pl, "gemm_mxfp4a8_gemv"); + const RadKernelInfo* rq = find(pl, "gated_quant_fp8"); + if (!rg || !rv || !rq || !rg->layout || !rg->relayout) { ok(nm, false, "row or hooks absent"); return; } + + Planes p; + p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"); + if (ic < 0 || is < 0) { ok(nm, false, "encoding has no codes/scale plane"); return; } + mxfp4_fill(p, ic, is, N, K, 0x51u, true); + std::vector lp = { PI("N", N), PI("K", K), PI("group", 32) }; + std::vector wq, ws, wr; + /* Stored through the gated row's own hooks (its `b_ref` is operand 4), so the gemv row reading + * the same bytes also checks that both ops store the planes in one form. */ + if (stored(rg, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(rg, lp, 3, p, { "scale" }, &ws) != RAD_OK || + stored(rg, lp, 4, p, { "scale" }, &wr) != RAD_OK) { + ok(nm, false, "relayout refused"); + return; + } + const int64_t nkb = K / 128, n = N / 2, gkb = n / 128; + std::vector ha((size_t)(M * K)); + std::vector as((size_t)(M * (ablk ? nkb : 1))); + for (int64_t i = 0; i < M; ++i) { + if (ablk) + for (int64_t c = 0; c < nkb; ++c) + as[(size_t)(i * nkb + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * nkb + c)) % 97); + else + as[(size_t)i] = 0.0125f * (float)(1 + st_mix32((uint32_t)i ^ 0xa5u) % 5); + for (int64_t k = 0; k < K; ++k) rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, 0x3cu)); + } + void* d_a = dalloc(ha.size()); + void* d_s = dalloc(as.size() * 4); + void* d_w = dalloc(wq.size()); + void* d_e = dalloc(ws.size()); + void* d_r = dalloc(wr.size()); + void* d_y = dalloc((size_t)(M * N * 2)); + void* d_q[3] = { dalloc((size_t)(M * n)), dalloc((size_t)(M * n)), dalloc((size_t)(M * n)) }; + void* d_z[3] = { dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)) }; + void* d_b[2] = { dalloc((size_t)(M * n * 2)), dalloc((size_t)(M * n * 2)) }; + if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y || !d_q[2] || !d_z[2] || !d_b[1]) { + ok(nm, false, "hipMalloc failed"); + return; + } + st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice); + st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice); + const RadTensor ta = T(d_a, RAD_F8E4M3, { M, K }); + const RadTensor tas = ablk ? T(d_s, RAD_F32, { M, nkb }) : T(d_s, RAD_F32, { M }); + const RadTensor tw = T(d_w, RAD_U8, { (int64_t)wq.size() }), te = T(d_e, RAD_U8, { (int64_t)ws.size() }); + const RadTensor tr = T(d_r, RAD_U8, { (int64_t)wr.size() }); + + /* The pair. */ + RadTensor none = T(nullptr, RAD_F32, { 1 }); + absent(none); + int rc = launch_row(rv, { ta, tas, tw, te, T(d_y, RAD_BF16, { M, N }), none, tr }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }); + if (rc == RAD_OK) + rc = launch_row(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q[0], RAD_F8E4M3, { M, n }), + T(d_z[0], RAD_F32, { M, gkb }), T(d_b[0], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") }); + if (rc != RAD_OK) { ok(nm, false, "the pair: rc=" + std::to_string(rc)); return; } + + /* The fold, with and without the bf16 product. */ + const std::vector gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), + PS("dtype", "mxfp4a8"), PS("act", "silu") }; + for (int v = 1; v <= 2; ++v) { + st_memset(d_q[v], 0, (size_t)(M * n)); + st_memset(d_z[v], 0, (size_t)(M * gkb * 4)); + } + st_memset(d_b[1], 0, (size_t)(M * n * 2)); + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }), + T(d_z[1], RAD_F32, { M, gkb }), T(d_b[1], RAD_BF16, { M, n }) }, gp); + if (rc == RAD_OK) + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }), + T(d_z[2], RAD_F32, { M, gkb }), none }, gp); + if (rc != RAD_OK) { ok(nm, false, "the fold: rc=" + std::to_string(rc)); return; } + + std::vector c[3]; + std::vector z[3]; + for (int v = 0; v < 3; ++v) { + c[v].resize((size_t)(M * n)); + z[v].resize((size_t)(M * gkb)); + st_memcpy(c[v].data(), d_q[v], c[v].size(), hipMemcpyDeviceToHost); + st_memcpy(z[v].data(), d_z[v], z[v].size() * 4, hipMemcpyDeviceToHost); + } + std::vector b0((size_t)(M * n)), b1((size_t)(M * n)); + st_memcpy(b0.data(), d_b[0], b0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(b1.data(), d_b[1], b1.size() * 2, hipMemcpyDeviceToHost); + int nc = 0, nz = 0, nb = 0, nc2 = 0, nz2 = 0, live = 0; + for (size_t i = 0; i < c[0].size(); ++i) { + nc += c[0][i] != c[1][i]; + nc2 += c[0][i] != c[2][i]; + live += c[1][i] != 0; + } + for (size_t i = 0; i < z[0].size(); ++i) { + nz += std::memcmp(&z[0][i], &z[1][i], 4) != 0; + nz2 += std::memcmp(&z[0][i], &z[2][i], 4) != 0; + } + for (size_t i = 0; i < b0.size(); ++i) nb += b0[i] != b1[i]; + ok(nm, nc == 0 && nz == 0 && nb == 0 && nc2 == 0 && nz2 == 0 && live > (int)c[1].size() / 2, + "codes differ " + std::to_string(nc) + "/" + std::to_string(nc2) + ", scales " + + std::to_string(nz) + "/" + std::to_string(nz2) + ", bf16 " + std::to_string(nb) + + ", nonzero " + std::to_string(live) + " of " + std::to_string(c[1].size())); +} + /* ---- the audio generator's ops and their optional forms, against libref's arithmetic ---------- * * Each case builds its operands on the host, runs the row, and compares with the host port of the @@ -13140,6 +13261,31 @@ static void mx_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }; perf_row(pl, row, ts, ps, d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters); + /* At a gate_up shape the gemv row's GEMM is half of a pair: time the other half + * (gated_quant_fp8 over its output) and the fold that replaces both. */ + if (!std::strcmp(row, "gemm_mxfp4a8_gemv") && N % 256 == 0 && K % 128 == 0) { + const int64_t n = N / 2; + void* d_q = dalloc((size_t)(M * n)); + void* d_z = dalloc((size_t)(M * (n / 128) * 4)); + if (!d_q || !d_z) { std::printf(" gated: hipMalloc failed\n"); continue; } + RadTensor nob = T(nullptr, RAD_BF16, { M, n }); + absent(nob); + perf_row(pl, "gated_quant_fp8", { T(d_y, RAD_BF16, { M, N }), T(d_q, RAD_F8E4M3, { M, n }), + T(d_z, RAD_F32, { M, n / 128 }), nob }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") }, + d_y, (size_t)(M * N * 2), 1, (double)(M * N * 2), iters, 0); + const RadKernelInfo* rg = find(pl, "gemm_mxfp4a8_gated_gemv"); + std::vector gr; + if (rg && stored(rg, lp, 4, p, { "scale" }, &gr) == RAD_OK && gr == wr) + perf_row(pl, "gemm_mxfp4a8_gated_gemv", + { T(d_a, RAD_F8E4M3, { M, K }), T(d_s, RAD_F32, { M, nkb }), + T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }), + T(d_r, RAD_U8, { (int64_t)wr.size() }), T(d_q, RAD_F8E4M3, { M, n }), + T(d_z, RAD_F32, { M, n / 128 }), nob }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"), + PS("act", "silu") }, + d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters); + } } } @@ -27203,6 +27349,13 @@ static void device_phase(const Plugin& pl) { mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1088, 576, true); mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1056, 576, false); mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_decode", 5120, 5120, true); + /* The gated fold against the pair it replaces (gemv + gated_quant_fp8): Qwen's and + * TranslateGemma's per-rank gate_up at every M of the band, one group of 128 at the smallest + * K, and the per-row activation scale. */ + for (const int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8 }) mxfp4a8_gated_case(pl, m, 17408, 5120, true); + mxfp4a8_gated_case(pl, 8, 21504, 5376, true); + mxfp4a8_gated_case(pl, 3, 256, 128, true); + mxfp4a8_gated_case(pl, 5, 1024, 640, false); /* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any * kernel's tile, two and three parts, at every band. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144); From a596f68782aef31557d11185e179a699415d9a71 Mon Sep 17 00:00:00 2001 From: mici81 Date: Tue, 20 Oct 2026 05:36:49 +0000 Subject: [PATCH 07/27] gemm_nt_q_gated_mx at gelu_tanh: the GeGLU MLP's gate_up, gelu_mul and quant_act_fp8 in one launch TranslateGemma's MLP over MXFP4 runs gate_up, gelu_mul into a bf16 plane and quant_act_fp8 over it before down. The gated fold now takes act gelu_tanh: gelu_mul's tanh GELU with its constants, the product rounded to bf16 as gelu_mul stores it, then quant_act_fp8's quantiser (the same arithmetic as gated_quant_fp8's). Byte-identical to the three-op chain (selftest at M = 1, 4, 8 on TranslateGemma's per-rank gate_up, the smallest shape and the per-row scale); the replaces-hook gives the chain. The GeGLU form writes no out_bf16: the chain's bf16 plane is gelu_mul's own output, which the hook cannot hand to an optional operand, and the shim refuses one. The gemma3 plugin declares the fold at up to 8 rows when both MLP linears are MXFP4 and no calibration tap reads the bf16 plane. TranslateGemma alone, speculation 7, two rounds each: one stream 144.5 / 144.9 -> 151.5 / 150.5 t/s, four streams (32 rows a step, past the band) unchanged; greedy translations identical. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/gemma3/gemma3.cpp | 35 +++++++++++++++++++++++--- docs/OPS.md | 3 ++- libr4d/r4d_fuse.cpp | 24 +++++++++++++++--- libr4d/r4d_gemm_mxfp4a8_gemv.hip | 38 ++++++++++++++++------------ libr4d/r4d_rows.cpp | 7 +++--- libr4d/r4d_selftest.cpp | 43 ++++++++++++++++++++++++-------- 6 files changed, 113 insertions(+), 37 deletions(-) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index f9efb790..0932362f 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -655,6 +655,11 @@ struct Gemma3Mlp { G3Linear ln_gu{}, ln_down{}; rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; rad_op op_gq = 0; + /* gate|up, the GeGLU and down's E4M3 quantiser in one launch (libr4d gemm_nt_q_gated_mx at + * gelu_tanh) at up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the + * GEMM, gelu_mul and quant_act_fp8 it replaces. */ + rad_op op_fold = 0; + int64_t fold_rows = 0; /* Calibration: gate|up's input and down's (this rank's columns). */ G3Tap tap_gu{}, tap_dn{}; const bool* tap_live = nullptr; @@ -725,6 +730,21 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.gu}, {ln_down.q8, ln_down.s8}); + // Not under calibration either: the down tap reads the bf16 product, which the fold never writes. + { + const int64_t hi = g.max_tok < 8 ? g.max_tok : 8; + if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 && + ln_gu.N % 256 == 0 && ln_gu.K % RAD_FP8_BLOCK == 0 && + rad_op_declared(b, "gemm_nt_q_gated_mx")) { + op_fold = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", ln_gu.N), RAD_INT("K", ln_gu.K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_STR("act", "gelu_tanh")), + RAD_WEIGHTS(ln_gu.w, ln_gu.ws, ln_gu.wref)), + {ln_gu.q8, ln_gu.s8}, {ln_down.q8, ln_down.s8}); + if (op_fold) fold_rows = hi; + } + } if (g.world > 1) op_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), @@ -754,14 +774,23 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, bool ar_fused) const { const int64_t T = batch->n_tok; + const bool fold = op_fold && T <= fold_rows; if (entry_done) { - ln_gu.gemm(c, w.gu, T); + if (!fold) ln_gu.gemm(c, w.gu, T); } else { RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); - ln_gu.step(c, w.h, w.gu, T); + if (!fold) + ln_gu.step(c, w.h, w.gu, T); + else if (!ln_gu.shared_in) + RAD_ISSUE_N(c, ln_gu.op_q, T, brows(w.h, T), brows(ln_gu.q8, T), brows(ln_gu.s8, T)); tap_gu.step(c, w.h, T, tap_live); } - if (op_gq) { + if (fold) { + RAD_ISSUE_N(c, op_fold, T, brows(ln_gu.q8, T), brows(ln_gu.s8, T), RAD_W(ln_gu.w), + RAD_W(ln_gu.ws), RAD_W(ln_gu.wref), brows(ln_down.q8, T), brows(ln_down.s8, T), + RAD_NONE); + ln_down.gemm(c, w.h, T); + } else if (op_gq) { RAD_ISSUE_N(c, op_gq, T, brows(w.gu, T), brows(ln_down.q8, T), brows(ln_down.s8, T), RAD_NONE); ln_down.gemm(c, w.h, T); } else { diff --git a/docs/OPS.md b/docs/OPS.md index 95840ce5..e318ea90 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -607,7 +607,8 @@ another. `gemm_nt_q_gated_mx` is the same fold over an OCP-MXFP4 weight (`dtype` `mxfp4a8`, `group` 32), which `gemm_nt_q` reads with the per-row reference exponent `b_ref` after `b_scale`. A schema of its own -because an op's operand count is fixed for the plugins built against it. +because an op's operand count is fixed for the plugins built against it. `act` `gelu_tanh` is the +GeGLU form, `gemm_nt_q` then `gelu_mul` then `quant_act_fp8`; it writes no `out_bf16`. `swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 8db942ae..7b11411f 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -518,7 +518,8 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre * * The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the * weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not - * mirrored. + * mirrored. At act gelu_tanh the chain is three steps, gelu_mul into a second temporary and + * quant_act_fp8 over it; that form refuses `out_bf16` (the shim), so operand 7 is not wired. */ extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -528,16 +529,31 @@ extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED; if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED; if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED; - if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; + const bool gelu = act_is(p, n_p, "silu", "gelu_tanh"); + if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; - switch (step) { - case 0: { + if (step == 0) { Step s(out, "gemm_nt_q"); s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K") .mirror(p, n_p, "group").mirror(p, n_p, "dtype"); /* a, a_scale, b, b_scale, y, a_sum, b_ref */ return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 }); } + if (gelu) { + if (step == 1) { + Step s(out, "gelu_mul"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pstr("dtype", "bf16"); + return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1) }); /* gate_up, y */ + } + if (step == 2) { + Step s(out, "quant_act_fp8"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128) + .pstr("dtype", "bf16"); + return s.wire({ RAD_FUSE_TMP(1), 5, 6 }); /* x, q, scale */ + } + return RAD_E_NOTFOUND; + } + switch (step) { case 1: { Step s(out, "gated_quant_fp8"); s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128) diff --git a/libr4d/r4d_gemm_mxfp4a8_gemv.hip b/libr4d/r4d_gemm_mxfp4a8_gemv.hip index 6c2e738b..3dc6c2ad 100644 --- a/libr4d/r4d_gemm_mxfp4a8_gemv.hip +++ b/libr4d/r4d_gemm_mxfp4a8_gemv.hip @@ -363,7 +363,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) { // Only one partial is live at a time, which is why the chunks are taken in that order rather than // in K order. The scaled sum is rounded to bf16 by the same conversion, and from there the arithmetic // is r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's -// amax, scale amax / 448, codes through q8_pack4. +// amax, scale amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's tanh GELU with +// its constants (r4d_model_bf16.hip), the product rounded to bf16 as gelu_mul stores it, then +// quant_act_fp8's quantiser, which is the same arithmetic as gated_quant_fp8's. namespace { __device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } __device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf @@ -372,7 +374,7 @@ __device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_ } } // namespace -template +template __global__ __launch_bounds__(16 * 32) void r4d_gemm_mxfp4a8_gated_kernel( const unsigned char* __restrict__ A, const float* __restrict__ As, @@ -447,7 +449,8 @@ void r4d_gemm_mxfp4a8_gated_kernel( #pragma unroll for (int j = 0; j < 4; ++j) { const float g = mxg_bf2f(sG[t][m][cc + j]); - const float a = g / (1.0f + expf(-g)); + const float a = ACT == 0 ? g / (1.0f + expf(-g)) + : 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g))); const uint16_t h = mxg_f2bf(a * mxg_bf2f(sG[8 + t][m][cc + j])); if (Y) Y[(size_t)m * y_ld + gcol + j] = h; vq[j] = mxg_bf2f(h); @@ -462,21 +465,19 @@ void r4d_gemm_mxfp4a8_gated_kernel( } namespace { -void mxgg_launch(bool ablk, const void* a, const void* as, const void* w, const void* ws, +void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws, const void* wr, void* q, void* s, void* y, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld, RadStream stream) { const dim3 grid((uint32_t)(n / 128)), block(16 * 32); hipStream_t st = (hipStream_t)stream; - if (ablk) - hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, - (const unsigned char*)a, (const float*)as, (const unsigned char*)w, - (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, - (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld); - else - hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, - (const unsigned char*)a, (const float*)as, (const unsigned char*)w, - (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, - (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld); +#define MXGG_L(AB_, ACT_) \ + hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, \ + (const unsigned char*)a, (const float*)as, (const unsigned char*)w, \ + (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \ + (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld) + if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); } + else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); } +#undef MXGG_L } } // namespace @@ -499,8 +500,13 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { if (q->rank != 2 || sc->rank != 2 || x->rank < 2) return R4D_NO(RAD_E_SHAPE); if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE); + /* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is + * gelu_mul's output, which the fold's replaces-hook cannot hand to the optional `out_bf16`, so + * that form writes none. */ const char* act = r4d_gets(a, "act"); - if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED); + const int actm = !act ? -1 : !std::strcmp(act, "silu") ? 0 : !std::strcmp(act, "gelu_tanh") ? 1 : -1; + if (actm < 0) return R4D_NO(RAD_E_UNSUPPORTED); + if (actm == 1 && y) return R4D_NO(RAD_E_UNSUPPORTED); /* The gated width from `q`, the buffer written; N and K from the op's parameters, since the * weight operands are packed bytes. */ @@ -531,7 +537,7 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { return R4D_NO(RAD_E_ALIGN); R4D_TRY("gemm_mxfp4a8_gated", - mxgg_launch(ablk, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data, + mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data, y ? y->data : nullptr, (int)M, (int)K, (int)nout, (int)as_rs, (int)lda, (int)N, (int)qp, (int)sp, (int)yp, s)); return RAD_OK; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 70906ab5..98268971 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4830,7 +4830,7 @@ static const RadConstraint cGemmNtQGatedFp8[] = { * per 128-column group of the gated output (N/2 a multiple of 128). */ static const RadConstraint cGemmNtQGatedMx[] = { C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"), - C_IN("act", "silu"), + C_IN("act", "silu gelu_tanh"), }; static const RadConstraint cGateQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), @@ -7771,11 +7771,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "block per 128-column group of the gated output, a wave per gate or up tile running all of that " "form's K partials in its order, so the [M, 2n] bf16 product is never written", "M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column " - "scale group); act silu only; the skinny kernel's fragment-order weight, [K/32][N] E8M0 " + "scale group); act silu, or gelu_tanh without out_bf16; the skinny kernel's fragment-order weight, [K/32][N] E8M0 " "exponents and per-row reference exponent, gate rows then up rows", "e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K, and the " "QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 " - "product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8", + "product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8 (silu), or by gelu_mul " + "and quant_act_fp8 (gelu_tanh)", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmNtQGatedMx), NOTUNE, nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, nullptr, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 39a17c4e..5d3b01c5 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6080,16 +6080,22 @@ static void w4a8_multi_user_exact(const Plugin& pl) { * gated row shares) and activation. Codes, scales and the bf16 product must be identical, and the * codes mostly non-zero (zeroed buffers compare equal). Run twice: with `out_bf16`, and without it, * where the codes and scales must still match. */ -static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk) { +static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk, + bool gelu = false) { const char* row = "gemm_mxfp4a8_gated_gemv"; if (!sel(row)) return; - char nm[160]; - std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + gated_quant_fp8, M=%lld N=%lld K=%lld%s", - row, (long long)M, (long long)N, (long long)K, ablk ? " ascale=row x 128" : ""); + char nm[192]; + std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + %s, M=%lld N=%lld K=%lld%s", row, + gelu ? "gelu_mul + quant_act_fp8" : "gated_quant_fp8", (long long)M, (long long)N, + (long long)K, ablk ? " ascale=row x 128" : ""); const RadKernelInfo* rg = find(pl, row); const RadKernelInfo* rv = find(pl, "gemm_mxfp4a8_gemv"); - const RadKernelInfo* rq = find(pl, "gated_quant_fp8"); - if (!rg || !rv || !rq || !rg->layout || !rg->relayout) { ok(nm, false, "row or hooks absent"); return; } + const RadKernelInfo* rq = find(pl, gelu ? "quant_act_fp8" : "gated_quant_fp8"); + const RadKernelInfo* rm = find(pl, "gelu_mul_bf16"); + if (!rg || !rv || !rq || (gelu && !rm) || !rg->layout || !rg->relayout) { + ok(nm, false, "row or hooks absent"); + return; + } Planes p; p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); @@ -6145,15 +6151,23 @@ static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K absent(none); int rc = launch_row(rv, { ta, tas, tw, te, T(d_y, RAD_BF16, { M, N }), none, tr }, { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }); - if (rc == RAD_OK) + if (rc == RAD_OK && !gelu) rc = launch_row(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q[0], RAD_F8E4M3, { M, n }), T(d_z[0], RAD_F32, { M, gkb }), T(d_b[0], RAD_BF16, { M, n }) }, { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") }); - if (rc != RAD_OK) { ok(nm, false, "the pair: rc=" + std::to_string(rc)); return; } + if (rc == RAD_OK && gelu) { + rc = launch_row(rm, { T(d_y, RAD_BF16, { M, N }), T(d_b[0], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(rq, { T(d_b[0], RAD_BF16, { M, n }), T(d_q[0], RAD_F8E4M3, { M, n }), + T(d_z[0], RAD_F32, { M, gkb }) }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16") }); + } + if (rc != RAD_OK) { ok(nm, false, "the chain: rc=" + std::to_string(rc)); return; } - /* The fold, with and without the bf16 product. */ + /* The fold, with and without the bf16 product (the GeGLU form refuses it, asserted). */ const std::vector gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), - PS("dtype", "mxfp4a8"), PS("act", "silu") }; + PS("dtype", "mxfp4a8"), PS("act", gelu ? "gelu_tanh" : "silu") }; for (int v = 1; v <= 2; ++v) { st_memset(d_q[v], 0, (size_t)(M * n)); st_memset(d_z[v], 0, (size_t)(M * gkb * 4)); @@ -6161,6 +6175,12 @@ static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K st_memset(d_b[1], 0, (size_t)(M * n * 2)); rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }), T(d_z[1], RAD_F32, { M, gkb }), T(d_b[1], RAD_BF16, { M, n }) }, gp); + if (gelu) { + if (rc == RAD_OK) { ok(nm, false, "the GeGLU fold served out_bf16"); return; } + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }), + T(d_z[1], RAD_F32, { M, gkb }), none }, gp); + st_memcpy(d_b[1], d_b[0], (size_t)(M * n * 2), hipMemcpyDeviceToDevice); + } if (rc == RAD_OK) rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }), T(d_z[2], RAD_F32, { M, gkb }), none }, gp); @@ -27356,6 +27376,9 @@ static void device_phase(const Plugin& pl) { mxfp4a8_gated_case(pl, 8, 21504, 5376, true); mxfp4a8_gated_case(pl, 3, 256, 128, true); mxfp4a8_gated_case(pl, 5, 1024, 640, false); + for (const int64_t m : { 1, 4, 8 }) mxfp4a8_gated_case(pl, m, 21504, 5376, true, true); + mxfp4a8_gated_case(pl, 3, 256, 128, true, true); + mxfp4a8_gated_case(pl, 2, 1024, 640, false, true); /* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any * kernel's tile, two and three parts, at every band. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144); From cbc299417e4de5557c3c3407f5dc956c12a46fab Mon Sep 17 00:00:00 2001 From: mici81 Date: Tue, 20 Oct 2026 15:30:18 +0000 Subject: [PATCH 08/27] gemm_mxfp4a8_gated_gemv: a block per gate/up tile pair, the group quantised by its last block One block a 128-column group left the grid at n / 128 blocks (68 at Qwen per rank on 32 WGPs) and the fold lost to the pair it replaces. Now the gemv row grid and K order, the bf16 product and row amaxes through the op scratch, an arrival counter per group keyed on the output. Byte for byte the old fold (selftest, twice into one output); r4d_selftest launch_row sizes scratch. Co-Authored-By: Claude Opus 5.5 (1M context) --- libr4d/r4d_gemm_mxfp4a8_gemv.hip | 238 +++++++++++++++++++++---------- libr4d/r4d_plugin.h | 1 + libr4d/r4d_rows.cpp | 18 +-- libr4d/r4d_selftest.cpp | 16 ++- 4 files changed, 188 insertions(+), 85 deletions(-) diff --git a/libr4d/r4d_gemm_mxfp4a8_gemv.hip b/libr4d/r4d_gemm_mxfp4a8_gemv.hip index 3dc6c2ad..10cb8e57 100644 --- a/libr4d/r4d_gemm_mxfp4a8_gemv.hip +++ b/libr4d/r4d_gemm_mxfp4a8_gemv.hip @@ -30,7 +30,7 @@ // shuffles. TN only widens a block; the sum order of a column is fixed by KW, which is constant. // // The column's 2^(ref - 127) is applied once, as in the decode kernel's epilogue. No scratch and no -// counters: there is no split across blocks. +// counters: there is no split across blocks (the gated fold at the end of the file has both). #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -40,11 +40,15 @@ #include #include #include +#include +#include #include +#include #define R4D_MXG_MAX_M 8 #define R4D_MXG_WMMA_MAX_M 64 // the WMMA form's bound: four 16-row tiles a wave #define R4D_MXG_KW 8 // waves on a block's K, both forms; a constant, so the sum order is too +#define R4D_MXGG_MAX_GROUPS 1024 // the gated fold's counter block: a gated width up to 131072 typedef unsigned mxg_u4 __attribute__((ext_vector_type(4))); typedef unsigned mxg_u2 __attribute__((ext_vector_type(2))); @@ -352,20 +356,34 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) { // ============================================================== the gated form (gemm_nt_q_gated_mx) // // The gate_up GEMM with gated_quant_fp8's pass in its epilogue, so the [M, 2n] bf16 product is never -// written and the quantiser is not a launch of its own. One block a 128-column group of the gated -// output (one activation scale group of the down projection's input): sixteen waves, one 16-column -// weight tile each -- the group's eight gate tiles (weight rows 128 g ..) and its eight up tiles (rows -// n + 128 g ..). +// written and the quantiser is not a launch of its own. A block is one 16-column tile of the gated +// output: sixteen waves, the WMMA form's eight K waves over the gate tile (weight rows 16 j ..) and +// eight over the up tile (rows n + 16 j ..), each tile's partials met in LDS in that form's order. +// The block forms silu(gate) * up in bf16 for its sixteen columns and each row's amax over them. The +// quantiser's scale is per 128 columns (one activation scale group of the down projection's input), +// so the eight blocks of a group leave their products and amaxes in the op's scratch, and the last +// to arrive (an agent-scope counter per group, keyed on the output as the decode row's) takes the +// group's amax and writes its codes and scales. // -// Byte-identical to the WMMA form above followed by gated_quant_fp8. A wave runs, for its tile, what -// all R4D_MXG_KW waves of that kernel run: partial v sums chunks v, v + KW, .. in order, and the -// partials are added v = 0, 1, .. from zero, as that kernel's epilogue adds its waves' rows of sP. -// Only one partial is live at a time, which is why the chunks are taken in that order rather than -// in K order. The scaled sum is rounded to bf16 by the same conversion, and from there the arithmetic -// is r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's -// amax, scale amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's tanh GELU with -// its constants (r4d_model_bf16.hip), the product rounded to bf16 as gelu_mul stores it, then -// quant_act_fp8's quantiser, which is the same arithmetic as gated_quant_fp8's. +// Why a tile pair a block: one block a 128-column group, each wave running every K partial of one of +// its sixteen tiles, left the grid at n / 128 blocks, 68 at Qwen's per-rank gate_up on 32 WGPs, so a +// few WGPs ran a third block while the rest idled, and the fold (97..101 us) lost to the gemv row and +// gated_quant_fp8 it replaces (78 + 7 us). Splitting K across a group's blocks instead moved an fp32 +// partial of the whole product per split through memory (4.4 MB at eight rows; 106 us). A tile pair +// a block is the gemv row's own grid and K order; what crosses blocks is the bf16 product and the +// amaxes, M * n * 2 bytes and n / 16 * M floats: Qwen 78..81 us, TranslateGemma 99 (as before), at +// TP1 148 against the pair's 152 (r4d_selftest --perfmx). End to end the gain is smaller, since a +// replayed step overlaps the old fold's idle WGPs with other work: Qwen without speculation x1 / x4 / +// x8 +1.4 / +1.8 / +1.5 % (three alternating rounds). +// +// Byte-identical to the WMMA form above followed by gated_quant_fp8. Wave v of a tile runs what wave +// v of that form runs (partial v sums chunks v, v + KW, .. in order), and the partials are added +// v = 0, 1, .. from zero, as that form's epilogue adds its waves' rows of sP. The scaled sum is +// rounded to bf16 by the same conversion, and from there the arithmetic is r4d_fused_quant_fp8.hip's +// gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's amax (a max, so the blocks' +// order does not matter), scale amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's +// tanh GELU with its constants (r4d_model_bf16.hip), the product rounded to bf16 as gelu_mul stores +// it, then quant_act_fp8's quantiser, which is the same arithmetic as gated_quant_fp8's. namespace { __device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } __device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf @@ -375,106 +393,160 @@ __device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_ } // namespace template -__global__ __launch_bounds__(16 * 32) +__global__ __launch_bounds__(2 * R4D_MXG_KW * 32) void r4d_gemm_mxfp4a8_gated_kernel( const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, uint8_t* __restrict__ Q, float* __restrict__ S, - uint16_t* __restrict__ Y, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, - int y_ld) { + uint16_t* __restrict__ Y, uint16_t* __restrict__ H, float* __restrict__ X, + unsigned* __restrict__ cnt, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, + int s_ld, int y_ld) { constexpr int KW = R4D_MXG_KW; - __shared__ uint16_t sG[16][R4D_MXG_MAX_M][16]; // bf16 gate (waves 0..7) and up (8..15) + __shared__ float sP[2][KW][R4D_MXG_MAX_M][16]; // gate (0) and up (1) partials, a K wave each + __shared__ unsigned s_last; const int lane = threadIdx.x & 31; const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5); - const int nt = (wave >> 3) * (n >> 4) + blockIdx.x * 8 + (wave & 7); // this wave's weight tile + const int half = wave >> 3, kv = wave & 7; // gate or up, and this wave's K partial + const int j = blockIdx.x; // the gated output's 16-column tile + const int nt = half * (n >> 4) + j; // this wave's weight tile const int col = lane & 15, khalf = lane >> 4; const int row = col; const bool live = row < M; const int ksteps = K >> 4, chunks = K >> 7; const unsigned* __restrict__ Wp = (const unsigned*)W; const int ref = (int)Wref[nt * 16 + col]; - mxg_v8f sum = (mxg_v8f)(0.f); - for (int v = 0; v < KW; ++v) { - mxg_v8f tot = (mxg_v8f)(0.f); - for (int ch = v; ch < chunks; ch += KW) { - unsigned wv[8]; + mxg_v8f tot = (mxg_v8f)(0.f); + for (int ch = kv; ch < chunks; ch += KW) { + unsigned wv[8]; #pragma unroll - for (int s = 0; s < 8; ++s) - wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]); - int e8[4]; + for (int s = 0; s < 8; ++s) + wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]); + int e8[4]; #pragma unroll - for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col]; - mxg_v2i af[8]; + for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col]; + mxg_v2i af[8]; #pragma unroll - for (int s = 0; s < 8; ++s) { - if (live) { - const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8); - af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1]; - } else { - af[s][0] = 0; af[s][1] = 0; - } + for (int s = 0; s < 8; ++s) { + if (live) { + const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8); + af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1]; + } else { + af[s][0] = 0; af[s][1] = 0; } - mxg_v8f acc = (mxg_v8f)(0.f); -#pragma unroll - for (int s = 0; s < 8; ++s) { - unsigned lo, hi; - r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi); - mxg_v2i wf; - wf[0] = (int)lo; wf[1] = (int)hi; - acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc); - } - const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f; -#pragma unroll - for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]); } + mxg_v8f acc = (mxg_v8f)(0.f); #pragma unroll - for (int e = 0; e < 8; ++e) sum[e] += tot[e]; + for (int s = 0; s < 8; ++s) { + unsigned lo, hi; + r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi); + mxg_v2i wf; + wf[0] = (int)lo; wf[1] = (int)hi; + acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc); + } + const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f; +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]); } - // acc[e] (and so sum[e]): row (lane & 15), column khalf * 8 + e of the tile. + // tot[e]: row (lane & 15), column khalf * 8 + e of the tile. if (live) { #pragma unroll - for (int e = 0; e < 8; ++e) { - const int c = khalf * 8 + e; - const float rf = __int_as_float((int)Wref[nt * 16 + c] << 23); - const __hip_bfloat16 h = (__hip_bfloat16)(ABLK ? sum[e] * rf : sum[e] * rf * As[(size_t)row * as_rs]); - sG[wave][row][c] = *(const uint16_t*)&h; - } + for (int e = 0; e < 8; ++e) sP[half][kv][row][khalf * 8 + e] = tot[e]; } __syncthreads(); + // The tile pair's product: a thread a (row, column), sixteen lanes a row, so a row's amax is a + // shuffle within its sixteen. + const int g = j >> 3; // the 128-column group + const int tid = threadIdx.x; + if (tid < M * 16) { + const int m = tid >> 4, c = tid & 15; + float sg = 0.f, su = 0.f; +#pragma unroll + for (int w = 0; w < KW; ++w) sg += sP[0][w][m][c]; +#pragma unroll + for (int w = 0; w < KW; ++w) su += sP[1][w][m][c]; + const int cg = j * 16 + c, cu = n + j * 16 + c; + const float rg = __int_as_float((int)Wref[cg] << 23), ru = __int_as_float((int)Wref[cu] << 23); + const float am = ABLK ? 1.f : As[(size_t)m * as_rs]; + const __hip_bfloat16 hg = (__hip_bfloat16)(ABLK ? sg * rg : sg * rg * am); + const __hip_bfloat16 hu = (__hip_bfloat16)(ABLK ? su * ru : su * ru * am); + const float gv = mxg_bf2f(*(const uint16_t*)&hg); + const float a = ACT == 0 ? gv / (1.0f + expf(-gv)) + : 0.5f * gv * (1.0f + tanhf(0.7978845608028654f * (gv + 0.044715f * gv * gv * gv))); + const uint16_t h = mxg_f2bf(a * mxg_bf2f(*(const uint16_t*)&hu)); + if (Y) Y[(size_t)m * y_ld + cg] = h; + H[(size_t)m * n + cg] = h; + float mx = fabsf(mxg_bf2f(h)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor(mx, o, 16)); + if (c == 0) X[(size_t)j * M + m] = mx; + } + // Every thread's stores are ordered before the counter; then the group's last arriver quantises. + __threadfence(); + __syncthreads(); + if (tid == 0) + s_last = __hip_atomic_fetch_add(&cnt[g], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_last != 7u) return; + if (tid == 0) cnt[g] = 0u; // reset for the next launch + __threadfence(); // acquire, before reading the other blocks' // gated_quant_fp8: one wave a row, a lane four consecutive columns of the group. if (wave < M) { - const int m = wave, c0 = lane * 4, t = c0 >> 4, cc = c0 & 15; - const size_t gcol = (size_t)blockIdx.x * 128 + c0; + const int m = wave, c0 = lane * 4; + const size_t gcol = (size_t)g * 128 + c0; + float mx = 0.f; +#pragma unroll + for (int t = 0; t < 8; ++t) mx = fmaxf(mx, X[(size_t)(g * 8 + t) * M + m]); float vq[4]; #pragma unroll - for (int j = 0; j < 4; ++j) { - const float g = mxg_bf2f(sG[t][m][cc + j]); - const float a = ACT == 0 ? g / (1.0f + expf(-g)) - : 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g))); - const uint16_t h = mxg_f2bf(a * mxg_bf2f(sG[8 + t][m][cc + j])); - if (Y) Y[(size_t)m * y_ld + gcol + j] = h; - vq[j] = mxg_bf2f(h); - } - float mx = fmaxf(fmaxf(fabsf(vq[0]), fabsf(vq[1])), fmaxf(fabsf(vq[2]), fabsf(vq[3]))); - mx = r4d_wave_max(mx); + for (int i = 0; i < 4; ++i) vq[i] = mxg_bf2f(H[(size_t)m * n + gcol + i]); const float sc = mx > 0.0f ? mx * (1.0f / q8_top()) : 1.0f; - if (lane == 0) S[(size_t)m * s_ld + blockIdx.x] = sc; + if (lane == 0) S[(size_t)m * s_ld + g] = sc; const float inv = 1.0f / sc; *(uint32_t*)(Q + (size_t)m * q_ld + gcol) = q8_pack4(vq[0], vq[1], vq[2], vq[3], inv); } } namespace { +// The arrival counters, one block per output buffer, as the decode row's (mxd_out_ctr): not in the +// scratch, which other ops overwrite, since they must be zero at entry. One allocation per (device, +// output), kept zero by the reducer and never freed (a recorded pass replays the pointer). +unsigned* mxgg_out_ctr(const void* out) { + static std::mutex mu; + static std::map, unsigned*> blocks; + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return nullptr; + std::lock_guard lk(mu); + const auto key = std::make_pair(dev, out); + if (auto it = blocks.find(key); it != blocks.end()) return it->second; + unsigned* p = nullptr; + if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr; + if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) { + (void)hipFree(p); + return nullptr; + } + blocks.emplace(key, p); + return p; +} + +// The scratch: the bf16 product [M, n], then each tile's per-row amax [n / 16][M] fp32. +long long mxgg_h_bytes(long long M, long long n) { return (M * n * 2 + 255) / 256 * 256; } +long long mxgg_scratch_bytes(long long M, long long n) { + return mxgg_h_bytes(M, n) + (n / 16) * M * (long long)sizeof(float); +} + void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws, - const void* wr, void* q, void* s, void* y, int M, int K, int n, int as_rs, int lda, - int ldws, int q_ld, int s_ld, int y_ld, RadStream stream) { - const dim3 grid((uint32_t)(n / 128)), block(16 * 32); + const void* wr, void* q, void* s, void* y, void* scratch, unsigned* cnt, int M, + int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld, + RadStream stream) { + const dim3 grid((uint32_t)(n / 16)), block(2 * R4D_MXG_KW * 32); hipStream_t st = (hipStream_t)stream; + uint16_t* h = (uint16_t*)scratch; + float* x = (float*)((char*)scratch + mxgg_h_bytes(M, n)); #define MXGG_L(AB_, ACT_) \ hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, \ (const unsigned char*)a, (const float*)as, (const unsigned char*)w, \ (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \ - (uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld) + (uint16_t*)y, h, x, cnt, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld) if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); } else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); } #undef MXGG_L @@ -512,7 +584,8 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { * weight operands are packed bytes. */ const long long M = q->shape[0], nout = q->shape[1]; const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0); - if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128) return R4D_NO(RAD_E_SHAPE); + if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128 || nout / 128 > R4D_MXGG_MAX_GROUPS) + return R4D_NO(RAD_E_SHAPE); if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE); if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE); @@ -535,10 +608,23 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) || !r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4) return R4D_NO(RAD_E_ALIGN); + /* The cross-block product and amaxes are the op's scratch (sized by the hook below); a + * shorter one is refused. */ + if (!a->scratch || a->scratch_bytes < mxgg_scratch_bytes(M, nout)) return R4D_NO(RAD_E_SCRATCH); + unsigned* cnt = mxgg_out_ctr(q->data); + if (!cnt) return R4D_NO(RAD_E_NOMEM); R4D_TRY("gemm_mxfp4a8_gated", mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data, - y ? y->data : nullptr, (int)M, (int)K, (int)nout, (int)as_rs, (int)lda, (int)N, - (int)qp, (int)sp, (int)yp, s)); + y ? y->data : nullptr, a->scratch, cnt, (int)M, (int)K, (int)nout, (int)as_rs, + (int)lda, (int)N, (int)qp, (int)sp, (int)yp, s)); return RAD_OK; } + +/* The op's scratch: the product and amaxes at the band's widest M, from N (twice the gated + * width). */ +extern "C" int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0); + if (M < 1 || M > R4D_MXG_MAX_M || N < 256 || N % 256) return 0; + return (int64_t)mxgg_scratch_bytes(M, N / 2); +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 872dbf7b..73d6bc3c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -460,6 +460,7 @@ int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream); int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream); int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream); +int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs*); int r4d_rad_dequant_w4 (const RadArgs*, RadStream); int r4d_rad_rowtopk (const RadArgs*, RadStream); int64_t r4d_rad_rowtopk_scratch(const RadArgs*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 98268971..e5490245 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -7768,8 +7768,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, { "gemm_mxfp4a8_gated_gemv", "gemm_nt_q_gated_mx", "gemm", "the gemv row's WMMA form over a gate_up weight with gated_quant_fp8's pass in its epilogue: a " - "block per 128-column group of the gated output, a wave per gate or up tile running all of that " - "form's K partials in its order, so the [M, 2n] bf16 product is never written", + "block per 16-column tile of the gated output, that form's eight K waves on the gate tile and " + "eight on the up tile, the block's bf16 product and row amaxes in the op's scratch and the last " + "of a 128-column group's blocks to arrive writing its codes and scales, so the [M, 2n] bf16 " + "product is never written", "M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column " "scale group); act silu, or gelu_tanh without out_bf16; the skinny kernel's fragment-order weight, [K/32][N] E8M0 " "exponents and per-row reference exponent, gate rows then up rows", @@ -7779,7 +7781,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "and quant_act_fp8 (gelu_tanh)", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmNtQGatedMx), NOTUNE, - nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, nullptr, + nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, r4d_rad_gemm_mxfp4a8_gated_scratch, r4d_rad_layout_mxfp4_gated, r4d_rad_relayout_mxfp4_gated, nullptr, nullptr, /* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */ r4d_fuse_gemm_nt_q_gated_mx }, @@ -9746,11 +9748,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { * every collective the peer flags and exchange buffers the all-reduces own * * gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output; - * gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) split partial is the - * op's scratch and its arrival counters are keyed on the output alone; - * router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken at init, one - * per declared op and band). Concurrent launches never share these, so those four rows are - * concurrent. A new row with stream-ordered state belongs in the list above. + * gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) and + * gemm_mxfp4a8_gated_gemv's split partials are the op's scratch and their arrival counters are keyed + * on the output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance + * (taken at init, one per declared op and band). Concurrent launches never share these, so those + * five rows are concurrent. A new row with stream-ordered state belongs in the list above. * * lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they * update and refills the pools they read between steps with its own copies, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 5d3b01c5..06bcfb46 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -5999,6 +5999,15 @@ static int launch_row(const RadKernelInfo* r, std::vector ts, a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + if (r->scratch) { + const int64_t need = r->scratch(&a); + if (need < 0) return (int)need; + if (need > 0) { + a.scratch = dalloc((size_t)need); + a.scratch_bytes = need; + if (!a.scratch) return RAD_E_NOMEM; + } + } const int rc = r->launch(&a, (RadStream)nullptr); if (rc != RAD_OK) return rc; return st_stream_sync(nullptr) == hipSuccess ? RAD_OK : RAD_E_STATE; @@ -6181,9 +6190,14 @@ static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K T(d_z[1], RAD_F32, { M, gkb }), none }, gp); st_memcpy(d_b[1], d_b[0], (size_t)(M * n * 2), hipMemcpyDeviceToDevice); } - if (rc == RAD_OK) + /* Twice into one output, cleared between: the split's arrival counters are keyed on the output, + * so the second launch reduces only if the first left them zero. */ + for (int rep = 0; rep < 2 && rc == RAD_OK; ++rep) { + st_memset(d_q[2], 0, (size_t)(M * n)); + st_memset(d_z[2], 0, (size_t)(M * gkb * 4)); rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }), T(d_z[2], RAD_F32, { M, gkb }), none }, gp); + } if (rc != RAD_OK) { ok(nm, false, "the fold: rc=" + std::to_string(rc)); return; } std::vector c[3]; From 2721f7c95107aa0eb3185fe11f3e635651004675 Mon Sep 17 00:00:00 2001 From: mici81 Date: Thu, 22 Oct 2026 12:28:20 +0000 Subject: [PATCH 09/27] MXFP4 gated fold: review fixes and docs The parts of the series' review rounds that concern the fold, carried over when the series was split: - gemm_mxfp4a8_gated_gemv: operand dtypes checked, the activation scale grid read as the gemm_nt_q rows read it (mx_ascale_grid), row pitches checked against the widths; the arrival counters are zeroed before any launch reads them (the memset is on the null stream, which the engine's streams need not wait for). - The layout hooks refuse an operand the gated row does not have; the GeGLU chain refuses out_bf16 (its bf16 plane is a temporary there). - r4d_selftest: the reference plane through the gemv row's own hook must be the same bytes; the small gated cases at K 256. - libr4d/README.md and docs/TOOLS.md: the row, and --perfmxd's fold timing. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/gemma3/gemma3.cpp | 1 + docs/TOOLS.md | 2 +- libr4d/README.md | 18 ++++++++++++++-- libr4d/r4d_fuse.cpp | 3 +++ libr4d/r4d_gemm_mxfp4a8_gemv.hip | 35 ++++++++++++++++++-------------- libr4d/r4d_layout.cpp | 12 +++++++---- libr4d/r4d_rows.cpp | 3 ++- libr4d/r4d_selftest.cpp | 14 +++++++++++-- 8 files changed, 63 insertions(+), 25 deletions(-) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 0932362f..deb2d3fb 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -733,6 +733,7 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const // Not under calibration either: the down tap reads the bf16 product, which the fold never writes. { const int64_t hi = g.max_tok < 8 ? g.max_tok : 8; + // G3Linear's mx is linear_is_mxfp4, never a rotated (ParoQuant) weight, so one part. if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 && ln_gu.N % 256 == 0 && ln_gu.K % RAD_FP8_BLOCK == 0 && rad_op_declared(b, "gemm_nt_q_gated_mx")) { diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 83eefecd..9948ea40 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -743,7 +743,7 @@ The `--perf*` modes time rows at one shape on a card. Two that cover the dense G | | | |---|---| | `--perf N K M [iters]` | the fp8 decode GEMMs, and the fp8 head (`logits_gemm_fp8`) | -| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches | +| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches; at a gate_up shape (N a multiple of 256, K of 128) also `gated_quant_fp8` and the fold that replaces the pair, `gemm_mxfp4a8_gated_gemv` | `--perfmx` is the MXFP4 expert GEMM (`M`, experts, `top_k`, skew), not the dense rows. `--cold MIB` times each launch alone behind a cache flush instead of back to back. diff --git a/libr4d/README.md b/libr4d/README.md index 27a2ff9a..f3e7598b 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -54,6 +54,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set. | `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny | | `gemm_mxfp4a8_gemv` | the same operands for one to eight rows: the weight streamed straight to registers, no LDS staging; WMMA when K is a multiple of 128, `v_dot4` otherwise, chosen from K alone so a row's bits do not depend on M | | `gemm_mxfp4a8_gemv_wide` | its WMMA form at 9..64 rows: up to four 16-row tiles a wave over each weight word, two 16-column tiles a block on wide, deep weights | +| `gemm_mxfp4a8_gated_gemv` | `gemm_nt_q_gated_mx`: the gemv WMMA form over a gate_up weight with `gated_quant_fp8`'s pass (or GeGLU's `gelu_mul` and `quant_act_fp8`) in its epilogue, M ≤ 8; the [M, 2n] product is never written | | `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch | | `gemm_mxfp4a8_decode_shortk` | the decode kernel at 33..64 rows of a wide, short weight (N ≥ 8192, K ≤ 2560), above `gemm_mxfp4a8_gemv_wide`, which loses there | | `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block | @@ -197,8 +198,21 @@ rows their outputs differ from the decode row's in the last bf16 place on a few thousand (within the selftest's bound). A greedy text can therefore differ from one produced with the decode row at those rows. Within the family a row's bits do not depend on M, as above. -**Tunables.** `gemv` and `gemv_wide` have none, so a `RADIANCE_TUNE` pin on `gemm_nt_q` passes -them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of +**`gemm_mxfp4a8_gated_gemv`** (`gemm_nt_q_gated_mx`, M ≤ 8, K a multiple of 128, N of 256, `act` +`silu`, or `gelu_tanh` without `out_bf16`). The `gemv` WMMA form over a gate_up weight, a block per +16-column tile pair of the gated output (eight K waves on the gate tile, eight on the up tile, in +`gemv`'s K order), the bf16 product and row amaxes in the op's scratch; the last of a 128-column +group's blocks to arrive (a counter keyed on the output) writes the group's codes and scales. Byte +for byte `gemm_mxfp4a8_gemv` followed by `gated_quant_fp8`, or by `gelu_mul` and `quant_act_fp8` +(`r4d_selftest`, M = 1..8, Qwen's and TranslateGemma's gate_up). A decode step of Qwen3.8-27B +at TP2 issues 631 kernels a card, and a dependent kernel costs 3.5-6.4 µs in a replayed graph on +gfx1201 however little it does, so the launch it saves is the point. TranslateGemma 27B alone, +one stream at speculation 7: 144.5 / 144.9 → 151.5 / 150.5 tok/s, measured with the first form of +this row (a block per 128-column group, the same bytes); the tile-pair form, Qwen3.8-27B without +speculation x1 / x4 / x8 +1.4 / +1.8 / +1.5 %. + +**Tunables.** `gemv`, `gemv_wide` and `gated_gemv` have none, so a `RADIANCE_TUNE` pin on +`gemm_nt_q` passes them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of those reaches both. A pin applies to every row serving the op, and an axis a serving row lacks stops startup by name. diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 7b11411f..f86f0726 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -531,6 +531,9 @@ extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED; const bool gelu = act_is(p, n_p, "silu", "gelu_tanh"); if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; + /* The GeGLU chain leaves its bf16 plane in a temporary, so a caller asking for out_bf16 there + * has no chain (the shim refuses the operand too). */ + if (gelu && RAD_FUSE_HAS(present, 7)) return RAD_E_UNSUPPORTED; if (step == 0) { Step s(out, "gemm_nt_q"); diff --git a/libr4d/r4d_gemm_mxfp4a8_gemv.hip b/libr4d/r4d_gemm_mxfp4a8_gemv.hip index 10cb8e57..151e84e0 100644 --- a/libr4d/r4d_gemm_mxfp4a8_gemv.hip +++ b/libr4d/r4d_gemm_mxfp4a8_gemv.hip @@ -520,7 +520,10 @@ unsigned* mxgg_out_ctr(const void* out) { if (auto it = blocks.find(key); it != blocks.end()) return it->second; unsigned* p = nullptr; if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr; - if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) { + // Zero before any launch reads it: the memset is on the null stream, which the engine's streams + // need not wait for, so wait here (as mxd_out_ctr and r4d_moe.hip's router counters do). + if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return nullptr; } @@ -569,7 +572,10 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { const RadTensor* sc = r4d_opt(a, MXGG_S); const RadTensor* y = r4d_opt(a, MXGG_Y); if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL); - if (q->rank != 2 || sc->rank != 2 || x->rank < 2) return R4D_NO(RAD_E_SHAPE); + if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || q->dtype != RAD_F8E4M3 || + sc->dtype != RAD_F32 || (y && y->dtype != RAD_BF16)) + return R4D_NO(RAD_E_DTYPE); + if (q->rank != 2 || sc->rank != 2 || x->rank != 2) return R4D_NO(RAD_E_SHAPE); if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE); /* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is @@ -590,21 +596,20 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE); if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE); - /* The activation scale per (row, 128 of K), or per row. */ - bool ablk; - long long as_rs; - if (xs->rank == 2 && xs->shape[0] == M && xs->shape[1] == K / 128) { - ablk = true; - as_rs = r4d_row_pitch(xs); - } else if (xs->rank == 1 && xs->shape[0] == M) { - ablk = false; - as_rs = 1; - } else { - return R4D_NO(RAD_E_SHAPE); - } + /* The activation scale grid as the gemm_nt_q rows read it (mx_ascale_grid), so the fold and the + * GEMM it replaces take every scale plane the same way. */ + GemmOps go{}; + go.ascale = xs; go.M = M; go.K = K; + int as_group = 0, as_rs_i = 1; + if (mx_ascale_grid(go, &as_group, &as_rs_i) != RAD_OK) return R4D_NO(RAD_E_SHAPE); + const bool ablk = as_group == 128; + const long long as_rs = as_rs_i; + /* Row pitches; r4d_row_pitch is -1 for a tensor not contiguous past its leading axis. A is read + * a dword at a time. */ const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); const long long yp = y ? r4d_row_pitch(y) : 0; - if (lda < 0 || as_rs < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + if (lda < K || lda % 4 || qp < nout || sp < nout / 128 || (y && yp < nout)) + return R4D_NO(RAD_E_STRIDE); if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) || !r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4) return R4D_NO(RAD_E_ALIGN); diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 8aa32ff5..c435b90e 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -942,20 +942,24 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand, /* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its * `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for * the reference plane in one form and the loader stores it once. */ -static int mx_gated_operand(int operand) { return operand == 4 ? Q_BREF : operand; } +static int mx_gated_operand(int operand) { + return operand == Q_B || operand == Q_BSCALE ? operand : operand == 4 ? Q_BREF : -1; +} extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { - return r4d_rad_layout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, out); + const int o = mx_gated_operand(operand); + return o < 0 ? RAD_E_UNSUPPORTED : r4d_rad_layout_mxfp4(p, n_p, o, enc, sel, pl, n, out); } extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, void* dst, int64_t dst_bytes) { - return r4d_rad_relayout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, dst, - dst_bytes); + const int o = mx_gated_operand(operand); + return o < 0 ? RAD_E_UNSUPPORTED + : r4d_rad_relayout_mxfp4(p, n_p, o, enc, sel, pl, n, dst, dst_bytes); } /* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index e5490245..a6fbb78d 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4827,7 +4827,8 @@ static const RadConstraint cGemmNtQGatedFp8[] = { C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"), }; /* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block - * per 128-column group of the gated output (N/2 a multiple of 128). */ + * per 16-column tile pair of the gated output; N/2 a multiple of 128, so each 128-column group's eight + * blocks meet at its last arriver, which quantises the group. */ static const RadConstraint cGemmNtQGatedMx[] = { C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"), C_IN("act", "silu gelu_tanh"), diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 06bcfb46..49db426e 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6121,6 +6121,16 @@ static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K ok(nm, false, "relayout refused"); return; } + /* The reference plane through the gemv row's own hook (its operand 6) must be the same bytes: + * a remap that handed the gated row's b_ref another form would otherwise pass, both kernels + * reading the same wrong plane. */ + { + std::vector wr_gemv; + if (stored(rv, lp, 6, p, { "scale" }, &wr_gemv) != RAD_OK || wr_gemv != wr) { + ok(nm, false, "b_ref stored differently by the gated and gemv rows"); + return; + } + } const int64_t nkb = K / 128, n = N / 2, gkb = n / 128; std::vector ha((size_t)(M * K)); std::vector as((size_t)(M * (ablk ? nkb : 1))); @@ -27388,10 +27398,10 @@ static void device_phase(const Plugin& pl) { * K, and the per-row activation scale. */ for (const int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8 }) mxfp4a8_gated_case(pl, m, 17408, 5120, true); mxfp4a8_gated_case(pl, 8, 21504, 5376, true); - mxfp4a8_gated_case(pl, 3, 256, 128, true); + mxfp4a8_gated_case(pl, 3, 256, 256, true); mxfp4a8_gated_case(pl, 5, 1024, 640, false); for (const int64_t m : { 1, 4, 8 }) mxfp4a8_gated_case(pl, m, 21504, 5376, true, true); - mxfp4a8_gated_case(pl, 3, 256, 128, true, true); + mxfp4a8_gated_case(pl, 3, 256, 256, true, true); mxfp4a8_gated_case(pl, 2, 1024, 640, false, true); /* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any * kernel's tile, two and three parts, at every band. */ From 0044d8d201ab2e9627bb1fc9a9238a5ced68fe97 Mon Sep 17 00:00:00 2001 From: mici81 Date: Fri, 23 Oct 2026 22:44:22 +0000 Subject: [PATCH 10/27] libr4d: check that a peer's push has landed before reducing it (2-rank family) A two-rank all-reduce or gather pushes its bytes into the peer's slot over PCIe P2P, drains its stores and then publishes a release flag; the peer reads the slot once it sees the flag. On 2x R9700 the bytes do not always land before the flag. With reads streaming beside the all-reduce (prefetch), a greedy reply differed from one server start to the next. A probe in ar_rmsnorm_quant_fp8 compared, right after the handshake, a plain load of the slot with a system-scope load and with the same word 100 us later: in about 1 launch in 1000 the reader saw the slot's previous contents, and the new bytes arrived about 1 us later, sometimes more. Pushed bytes wait in the writer's L2 until a system-scope release writes them back: with the flag sent before the push (a test mode) and nothing after it, they stayed invisible for the whole kernel (49 ms). The flag's release does write them back, but the writeback and the flag store reach the peer by different paths, so the flag can arrive first. A stronger drain on the writer (drain=1), PCIe relaxed ordering off on both cards and an HDP flush on the reader did not change that; acq=1 hides it only by delaying the reads (and costs 12-33 % of decode). The writer now sums a per-dword hash (MurmurHash3's finalizer over value and index) over what it pushes and stores the block's sum, salted with its handshake value, into the peer's check word for (slot, block): two parity slots of fine-grained words after the flags. The flag's release that follows writes the pushed bytes back. The reader reads the check word, sums the same over the bytes it is about to read and, until the two agree, takes an acquire fence, sleeps briefly and reads again; a push that never lands traps after 2 s. A stale element and a stale check word both disagree, so the order in which the two land does not matter. No value changes. Kernels: ar_rmsnorm_quant_fp8 (exact and 6-bit wire), r4d_ar_oneshot_2rank_exact, r4d_ar_hc_write, r4d_ar_gather_hc_write, r4d_ar_gather_2rank, r4d_ar_oneshot_2rank_wht6, r4d_ar_hc_write_wht6, ar_rmsnorm_quant_i8, r4d_ar_ln_had_quant_i8. Also: the link gate is released after the check, the exact and gather launchers round their width to whole waves (the check's wave sum reads all 32 lanes), and ln_had's dynamic LDS ceiling leaves room for the check's static words. Co-Authored-By: Claude Opus 5.5 (1M context) --- libr4d/r4d_ar_entry.hip | 4 +- libr4d/r4d_ar_gather_2rank.hip | 9 +++ libr4d/r4d_ar_ln_had_quant_i8.hip | 61 ++++++++++++-- libr4d/r4d_ar_oneshot_2rank_exact.hip | 31 ++++++- libr4d/r4d_ar_oneshot_2rank_wht6.h | 45 ++++++++++- libr4d/r4d_ar_oneshot_2rank_wht6.hip | 8 +- libr4d/r4d_ar_seq.h | 111 ++++++++++++++++++++++++++ libr4d/r4d_fused_quant_fp8.hip | 60 ++++++++++++-- libr4d/r4d_rmsnorm_quant_i8.hip | 12 ++- 9 files changed, 317 insertions(+), 24 deletions(-) diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 17458f71..6faed029 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -343,10 +343,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (host) { sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes); - fl = r4d_ar_host_alloc(flag_words * 4); + fl = r4d_ar_host_alloc((flag_words + 2L * maxb) * 4); } else { sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); - fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); + fl = r4d_ar_ipc_alloc((flag_words + 2L * maxb) * 4, 1, handle, &hlen); } sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); diff --git a/libr4d/r4d_ar_gather_2rank.hip b/libr4d/r4d_ar_gather_2rank.hip index fdbacfd3..d6fb113f 100644 --- a/libr4d/r4d_ar_gather_2rank.hip +++ b/libr4d/r4d_ar_gather_2rank.hip @@ -72,6 +72,7 @@ __global__ void r4d_ar_gather_2rank_kernel( const int w = (n16 + nb - 1) / nb; const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) // Push the chunk to the peer slot and place this rank's own slice (a local store, no handshake) // while the push is in flight. @@ -82,6 +83,8 @@ __global__ void r4d_ar_gather_2rank_kernel( v2 = in4[r4d_g_src(k + 2 * nt, row16, n16, sp16)], v3 = in4[r4d_g_src(k + 3 * nt, row16, n16, sp16)]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v0; out4[r4d_g_dst(k + nt, row16, n16, rank, dp16)] = v1; out4[r4d_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2; @@ -90,11 +93,13 @@ __global__ void r4d_ar_gather_2rank_kernel( for (; k < end; k += nt) { int4 v = in4[r4d_g_src(k, row16, n16, sp16)]; ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v; } } // Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot // see the flag before the data. + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -110,6 +115,9 @@ __global__ void r4d_ar_gather_2rank_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); // Place the peer's slice, now staged in this rank's scratch. { @@ -165,6 +173,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes r4d_ar_gather_2rank_kernel<<>>( (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, diff --git a/libr4d/r4d_ar_ln_had_quant_i8.hip b/libr4d/r4d_ar_ln_had_quant_i8.hip index 98d548ba..ccf5c776 100644 --- a/libr4d/r4d_ar_ln_had_quant_i8.hip +++ b/libr4d/r4d_ar_ln_had_quant_i8.hip @@ -163,6 +163,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( float* Lsc = (float*)(Lpk + (size_t)cpb * ARN_WV * ARN_NWORD); const int lig = lane & (ARN_LPG - 1), gw = lane / ARN_LPG; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) if constexpr (WIRE == 0) { // Push my rows to the peer slot. A row is K/8 16B words and rows are contiguous, so a row // range is a word range. @@ -173,8 +174,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( for (; k + 3 * THR < wend; k += 4 * THR) { int4 v0 = in4[k], v1 = in4[k + THR], v2 = in4[k + 2 * THR], v3 = in4[k + 3 * THR]; ps[k] = v0; ps[k + THR] = v1; ps[k + 2 * THR] = v2; ps[k + 3 * THR] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + THR)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * THR)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * THR)); } - for (; k < wend; k += THR) ps[k] = in4[k]; + for (; k < wend; k += THR) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } else { // Rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in // LDS. A wave owns whole chunks, so every lane emits exactly ARN_NWORD dwords per chunk and the @@ -201,8 +204,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( float scl = (a > 0.f) ? arn_bf16_round(a * (1.0f / (float)ARN_QMAX)) : 1.0f; if (!(scl > 0.f)) scl = 1.0f; if (lig == 0) { - p_sc[c * ARN_CG + gl] = (unsigned short)(__float_as_uint(scl) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(scl) >> 16); + p_sc[c * ARN_CG + gl] = sc16; Lsc[(size_t)ci * ARN_CG + gl] = scl; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); } const float inv = 1.0f / scl; #pragma unroll @@ -217,20 +222,30 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( // Flush lane-contiguously region by region, widest first, so each region is one coalesced // store of ARN_WV x width bytes (ARN_NWORD is 3). char* pb = p_pay + (size_t)c * ARN_CBYTES; + const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); // the chunk's first dword #pragma unroll - for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) + for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) { *(uint4*)(pb + w4 * 4 * ARN_WV + lane * 16) = make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]); - if constexpr (ARN_NWORD % 4 >= 2) + hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]), + cd + (unsigned)(w4 * ARN_WV + lane * 4)); + } + if constexpr (ARN_NWORD % 4 >= 2) { *(uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8) = make_uint2(acc[ARN_NWORD & ~3], acc[(ARN_NWORD & ~3) + 1]); - if constexpr (ARN_NWORD % 2 == 1) + const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2); + hck += r4d_archk_mix(acc[ARN_NWORD & ~3], e) + r4d_archk_mix(acc[(ARN_NWORD & ~3) + 1], e + 1u); + } + if constexpr (ARN_NWORD % 2 == 1) { *(unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4) = acc[ARN_NWORD - 1]; + hck += r4d_archk_mix(acc[ARN_NWORD - 1], cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane)); + } #pragma unroll for (int w = 0; w < ARN_NWORD; ++w) Lpk[((size_t)ci * ARN_NWORD + w) * ARN_WV + lane] = acc[w]; } } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -245,6 +260,35 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + if constexpr (WIRE == 0) { + const int wpr = K >> 3; + for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + } else { + for (int ci = wave; ci < cpb; ci += NW) { + const int c = c00 + ci; + const char* pb = m_pay + (size_t)c * ARN_CBYTES; + const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); +#pragma unroll + for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) + h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16), + cd + (unsigned)(w4 * ARN_WV + lane * 4)); + if constexpr (ARN_NWORD % 4 >= 2) { + const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8); + const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2); + h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); + } + if constexpr (ARN_NWORD % 2 == 1) + h += r4d_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4), + cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane)); +#pragma unroll + for (int t = 0; t < ARN_ITERS; ++t) { + const int gl = t * ARN_GPW + gw; + if (lig == 0) h += r4d_archk_mix(m_sc[c * ARN_CG + gl], R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); + } + } + } + }); // The peer's rows are now in my scratch, in the same [M, K] layout as X. const __hip_bfloat16* P = (const __hip_bfloat16*)ms; @@ -404,9 +448,10 @@ static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) { } return b; } -// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words (seq and slot), which -// the runtime places in front of it. -static constexpr size_t kArnLdsCap = 65536 - 16; +// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words, which the runtime places +// in front of it: seq and slot, and the push check's (r4d_ar_seq.h: two 32-word sums and a flag, +// 260 bytes), rounded up. +static constexpr size_t kArnLdsCap = 65536 - 16 - 512; // Fewest blocks at which this shape fits: each block owns ceil(M / nb) rows, and on the compressed // wire each row costs a staging slice and its chunks' packed half. -1 when no block count fits (a diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 37bbd373..f9e8893b 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -76,6 +76,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) // Push the chunk to the peer slot, 4x unrolled for memory-level parallelism. { @@ -83,8 +84,10 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( for (; k + 3 * nt < end; k += 4 * nt) { int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); } - for (; k < end; k += nt) ps[k] = in4[k]; + for (; k < end; k += nt) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } // Drain modes, ordering the pushes before the release flag so the peer sees data first: // 0 = none (relies on PCIe posted-write ordering and the release flag) @@ -94,6 +97,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( // 3 = all-thread s_wait_storecnt 0: every wave drains its posted writes with no L2 // writeback-invalidate; PCIe keeps posted writes to one peer ordered, so the release flag // lands after the data. Correct only for fine-grained memory (coarse leaves data in L2). + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -108,6 +112,9 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); // Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch). { int k = start + tid; @@ -147,15 +154,19 @@ __global__ void r4d_ar_hc_write_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { int4 v0 = y4[k], v1 = y4[k + nt], v2 = y4[k + 2 * nt], v3 = y4[k + 3 * nt]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); } - for (; k < end; k += nt) ps[k] = y4[k]; + for (; k < end; k += nt) { const int4 v = y4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -168,8 +179,11 @@ __global__ void r4d_ar_hc_write_kernel( } } __syncthreads(); - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); const int wpr = n >> 3; // 16B words a row for (int k = start + tid; k < end; k += nt) { @@ -231,6 +245,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) const int wpr = n >> 3; // 16B words a row const int row_lo = start / wpr; const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0; @@ -264,7 +279,9 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int4 out = r4d_ar_gather_word(G, inv, s_i, s_w, s_g, row, row - row_lo, i0); y4[k] = out; ps[k] = out; + hck += r4d_archk_u4(out, 4u * (unsigned)k); } + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -277,8 +294,11 @@ __global__ void r4d_ar_gather_hc_write_kernel( } } __syncthreads(); - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int k = start + tid; k < end; k += nt) { const int4 r = vadd<__hip_bfloat16, 8>(y4[k], ms[k]); @@ -398,6 +418,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes r4d_ar_hc_write_kernel<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, @@ -436,6 +457,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes /* Zeroed including padding: the struct is passed by value, so its tail padding is part of the * kernel-argument bytes a recorded pass's audit compares. */ R4dArGather G; @@ -527,6 +549,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes #define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<<>>( \ (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \ diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.h b/libr4d/r4d_ar_oneshot_2rank_wht6.h index 576747dc..0a2844cc 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.h +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.h @@ -129,7 +129,8 @@ struct Wht6Chunk { template __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_groups, int lane, int lig, int gw, uint4* p_pay, - unsigned short* p_sc, uint4* l_pay, float* l_sc) { + unsigned short* p_sc, uint4* l_pay, float* l_sc, + unsigned int& hck) { using Ch = Wht6Chunk; const int qmin = -(1 << (BITS - 1)), qmax = (1 << (BITS - 1)) - 1; unsigned int acc[Ch::NW]; @@ -157,8 +158,10 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group float sc = (a > 0.f) ? bf16_round(a * (1.0f / (float)qmax)) : 1.0f; if (!(sc > 0.f)) sc = 1.0f; if (lig == 0 && live) { - p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16); + p_sc[g] = sc16; l_sc[g] = sc; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g); } const float inv = 1.0f / sc; #pragma unroll @@ -177,6 +180,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane; p_pay[o] = q; l_pay[o] = q; + hck += r4d_archk_u4(q, 4u * (unsigned)o); } } else { unsigned int* pp = reinterpret_cast(p_pay); @@ -186,6 +190,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane; pp[o] = acc[u]; lp[o] = acc[u]; + hck += r4d_archk_mix(acc[u], (unsigned)o); } } } @@ -209,6 +214,34 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne if (acq) __threadfence_system(); } +// The push check's re-hash of one chunk (r4d_ar_seq.h): the payload words and live scales the +// reduce below reads, at the indices wht6_push_chunk hashed them. +template +__device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane, + int lig, int gw, const uint4* m_pay, + const unsigned short* m_sc) { + using Ch = Wht6Chunk; + if constexpr (Ch::U4) { +#pragma unroll + for (int u = 0; u < Ch::NW / 4; ++u) { + const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane; + h += r4d_archk_u4(m_pay[o], 4u * (unsigned)o); + } + } else { + const unsigned int* mp = reinterpret_cast(m_pay); +#pragma unroll + for (int u = 0; u < Ch::NW; ++u) { + const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane; + h += r4d_archk_mix(mp[o], (unsigned)o); + } + } +#pragma unroll + for (int t = 0; t < Ch::ITERS; ++t) { + const int g = c * CG + t * GPW + gw; + if (lig == 0 && g < n_groups) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + } +} + // Reduce: unpack both halves, add in fp32, inverse-rotate, pass each live group's EPL elements to st. template __device__ __forceinline__ void wht6_reduce_chunk(const St& st, int c, int n_groups, int lane, @@ -300,10 +333,16 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel( #pragma unroll for (int i = 0; i < EPL; ++i) v[i] = rd_to_f(in[off + i]); }; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) for (int c = c0 + wid; c < c1; c += nwarp) - wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc); + wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck); + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s); wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { + for (int c = c0 + wid; c < c1; c += nwarp) + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + }); const auto st = [&](long off, const float* v) { #pragma unroll diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.hip b/libr4d/r4d_ar_oneshot_2rank_wht6.hip index 67a2575a..0047c121 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.hip +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.hip @@ -139,10 +139,16 @@ __global__ void r4d_ar_hc_write_wht6_kernel( r4d_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow, reinterpret_cast(&q)); }; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) for (int c = c0 + wid; c < c1; c += nwarp) - wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc); + wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck); + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s); wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { + for (int c = c0 + wid; c < c1; c += nwarp) + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + }); r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int c = c0 + wid; c < c1; c += nwarp) diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index e9ae425c..2ce45081 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -87,3 +87,114 @@ __device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long wo __device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned int want) { return (int)(flag - want) < 0; } + +// ---- The push check. A peer's push over PCIe P2P can land after its release flag (measured on 2x +// R9700: the reader sometimes found the slot's previous contents right after the handshake, and +// the new bytes ~1 us later), so the flag alone does not say the bytes are there. The pushed bytes +// wait in the writer's L2 for the release's writeback, and that writeback and the flag store reach +// the peer by different paths. The writer sums +// mix(dword, index) over what it pushes and stores the block's sum, salted with its handshake +// value, into the peer's check word for (slot, block): fine-grained words after the flags +// (r4d_ar_entry.hip sizes the allocation). The reader sums the same over the bytes it is about to +// read and reads again until the two agree. A stale element and a stale check word (an older +// handshake value) both disagree, so only the landed push passes; the order the two land in does +// not matter. The sum is order-free, so writer and reader may split the bytes differently. +#define R4D_ARCHK_SALT 0x6C8E9CF5u +#ifndef R4D_ARCHK_DEADLINE +#define R4D_ARCHK_DEADLINE 200000000ull // wall_clock64 ticks (100 MHz): 2 s; a push that never lands is a lockstep fault +#endif +#define R4D_ARCHK_U16 0x80000000u // index space of 16-bit fields (wire scales), apart from dwords + +// MurmurHash3's finalizer over (value, index): every bit of the value reaches every bit of the term, +// so a sum of terms changes when any value does. A linear mix is not enough: (v ^ c_e) summed over +// a run of indices can lose v entirely, and a message of one repeated value (a test pattern, a +// zero-filled row) would then pass whatever the slot held. +__device__ __forceinline__ unsigned int r4d_archk_mix(unsigned int v, unsigned int e) { + unsigned int x = v ^ (e * 0x9E3779B9u); + x ^= x >> 16; x *= 0x85EBCA6Bu; + x ^= x >> 13; x *= 0xC2B2AE35u; + x ^= x >> 16; + return x; +} +// A 16B word at dword index `e`. +__device__ __forceinline__ unsigned int r4d_archk_u4(int4 v, unsigned int e) { + return r4d_archk_mix((unsigned int)v.x, e) + r4d_archk_mix((unsigned int)v.y, e + 1u) + + r4d_archk_mix((unsigned int)v.z, e + 2u) + r4d_archk_mix((unsigned int)v.w, e + 3u); +} +__device__ __forceinline__ unsigned int r4d_archk_u4(uint4 v, unsigned int e) { + return r4d_archk_mix(v.x, e) + r4d_archk_mix(v.y, e + 1u) + r4d_archk_mix(v.z, e + 2u) + + r4d_archk_mix(v.w, e + 3u); +} +// The check word of (slot, block) in a flags allocation: two parity slots of nbw words after the +// nbw flags. +__device__ __forceinline__ unsigned int* r4d_archk_word(unsigned int* flags, unsigned int nbw, + unsigned int slot, unsigned int b) { + return flags + nbw + slot * nbw + b; +} +__device__ __forceinline__ unsigned int r4d_archk_wave_sum(unsigned int h) { + for (int o = 16; o > 0; o >>= 1) h += __shfl_xor(h, o, 32); + return h; +} + +// Writer: every thread of the block calls this after its pushes, before the handshake's barrier. +// Thread 0 stores the block's sum into the peer's check word. +__device__ __forceinline__ void r4d_archk_put(unsigned int h, unsigned int* peer_flags, + unsigned int nbw, unsigned int slot, + unsigned int b, unsigned int seq, + bool release = false) { + __shared__ unsigned int s_ckp[32]; + const unsigned int tid = threadIdx.x, nt = blockDim.x; + h = r4d_archk_wave_sum(h); + if ((tid & 31u) == 0u) s_ckp[tid >> 5] = h; + __syncthreads(); + if (tid == 0) { + unsigned int t = 0u; + for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckp[w]; + /* The pushed bytes sit in this card's L2 until a system-scope release writes them back. The + * flag's release, right after this, does that, so the word itself can be relaxed (the reader + * re-reads until the bytes agree with it). Where the flag went out before the push (the test + * mode, drain 4) nothing else would write them back before the kernel ends: a release. */ + unsigned int* const cw = r4d_archk_word(peer_flags, nbw, slot, b); + if (release) + __hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); + else + __hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); + } +} + +// Reader: every thread of the block calls this after the handshake; `rehash(h)` adds the thread's +// share of the bytes the block is about to read, with the same loads the kernel then makes. +template +__device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned int nbw, + unsigned int slot, unsigned int b, + unsigned int seq, const F& rehash) { + __shared__ unsigned int s_ckw[32]; + __shared__ unsigned int s_ckok; + const unsigned int tid = threadIdx.x, nt = blockDim.x; + const unsigned long long t0 = tid == 0 ? wall_clock64() : 0ull; + for (;;) { + /* The check word first, so its round trip overlaps the re-hash's loads. Read before the bytes + * it is compared with, it can only be older than them, and an older word just fails this try. */ + const unsigned int want = tid == 0 ? __hip_atomic_load(r4d_archk_word(my_flags, nbw, slot, b), + __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) + : 0u; + unsigned int h = 0u; + rehash(h); + h = r4d_archk_wave_sum(h); + if ((tid & 31u) == 0u) s_ckw[tid >> 5] = h; + __syncthreads(); + if (tid == 0) { + unsigned int t = 0u; + for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckw[w]; + const bool ok = t + seq * R4D_ARCHK_SALT == want; + if (!ok && wall_clock64() - t0 > R4D_ARCHK_DEADLINE) __builtin_trap(); + s_ckok = ok ? 1u : 0u; + } + __syncthreads(); + if (s_ckok) return; + __syncthreads(); // s_ckw and s_ckok are rewritten by the next try + /* Drop the vector caches, so the next try reads the bytes from where the push lands. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); + __builtin_amdgcn_s_sleep(2); + } +} diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 4f9853f0..23c615d6 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -415,13 +415,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( unsigned int* const Lpk = (unsigned int*)loc_pack; float* const Lsc = (float*)(loc_pack + loc_scale_off); + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) if constexpr (WIRE == 0) { /* Push my rows into the peer's slot. `x` is a tight [M][n] of bf16 (the launcher refuses a * pitched one), so a row range is a 16B-word range. */ const int wpr = (int)(n >> 3); const int wend = r1 * wpr; const int4* const in4 = (const int4*)x; - for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) ps[k] = in4[k]; + for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) { + const int4 v = in4[k]; + ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); + } } else { /* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks, * so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is @@ -449,8 +454,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( float sc = (a > 0.0f) ? bf2f(f2bf(a * (1.0f / (float)ARQ_QMAX))) : 1.0f; if (!(sc > 0.0f)) sc = 1.0f; if (lig == 0) { - p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16); + p_sc[g] = sc16; Lsc[g] = sc; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g); } const float inv = 1.0f / sc; #pragma unroll @@ -464,21 +471,33 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( } /* Flush lane-contiguously, widest region first, so each is one coalesced store. */ char* const pb = p_pay + (size_t)c * ARQ_CBYTES; + const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); // the chunk's first dword #pragma unroll - for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) + for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) { *(uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16) = make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]); - if constexpr (ARQ_NWORD % 4 >= 2) + hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]), + cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); + } + if constexpr (ARQ_NWORD % 4 >= 2) { *(uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8) = make_uint2(acc[ARQ_NWORD & ~3], acc[(ARQ_NWORD & ~3) + 1]); - if constexpr (ARQ_NWORD % 2 == 1) + const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u; + hck += r4d_archk_mix(acc[ARQ_NWORD & ~3], e) + + r4d_archk_mix(acc[(ARQ_NWORD & ~3) + 1], e + 1u); + } + if constexpr (ARQ_NWORD % 2 == 1) { *(unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4) = acc[ARQ_NWORD - 1]; + hck += r4d_archk_mix(acc[ARQ_NWORD - 1], + cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); + } #pragma unroll for (int wi = 0; wi < ARQ_NWORD; ++wi) Lpk[((size_t)c * ARQ_NWORD + wi) * ARQ_WV + lane] = acc[wi]; } } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); /* The drain modes are r4d_ar_oneshot_2rank_exact's, selected by the same variant table. */ if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); @@ -495,6 +514,37 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + if constexpr (WIRE == 0) { + const int wpr = (int)(n >> 3); + const int4* const m4 = (const int4*)ms; + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) + h += r4d_archk_u4(m4[k], 4u * (unsigned)k); + } else { + for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) { + const int c = c00 + ci; + const char* const pb = m_pay + (size_t)c * ARQ_CBYTES; + const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); +#pragma unroll + for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) + h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16), + cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); + if constexpr (ARQ_NWORD % 4 >= 2) { + const uint2 u = *(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8); + const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u; + h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); + } + if constexpr (ARQ_NWORD % 2 == 1) + h += r4d_archk_mix(*(const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4), + cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); +#pragma unroll + for (int t = 0; t < ARQ_ITERS; ++t) { + const int g = c * ARQ_CG + t * ARQ_GPW + gw; + if (lig == 0) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + } + } + } + }); if constexpr (WIRE == 6) { /* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate, diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index b7b7596b..ef4371cf 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -324,7 +324,13 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( /* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */ const int wpr = (int)(n >> 3); const int4* const in4 = (const int4*)x; - for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) ps[k] = in4[k]; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) { + const int4 v = in4[k]; + ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); + } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -338,6 +344,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) + h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */ const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; From fa7a5e416461c727a5f92eed7cc10937d97d5693 Mon Sep 17 00:00:00 2001 From: mici81 Date: Fri, 23 Oct 2026 22:44:23 +0000 Subject: [PATCH 11/27] r4d_selftest: every push landing after its flag (the push check's regression case) A test-only mode of the two-rank exact all-reduce (drain 4, set by R4D_AR_TEST_LATE_PUSH=1 in the launcher, not in any tuning table): every block publishes its flag before its push, pushes about 20 us later and stores its check word as a release, since no flag release follows to write the bytes back. The new case runs the 32-round sweep of ar_oneshot_2rank_exact and its host twin under it. Without the push check the readers sum their slots' previous contents (16.5 million of 18.5 million elements wrong on the device row, 12.9 million on the host twin); with it every sum is exact. Co-Authored-By: Claude Opus 5.5 (1M context) --- libr4d/r4d_ar_oneshot_2rank_exact.hip | 16 ++++++++++++++-- libr4d/r4d_selftest.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index f9e8893b..773389b8 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -18,6 +18,7 @@ // * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the // fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are // selectable (default drain=1/acq=0 on fine-grained). +#include #include "r4d.h" #include "r4d_ar_seq.h" #include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire @@ -78,6 +79,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( int end = start + w; if (end > n16) end = n16; unsigned int hck = 0u; // the push check (r4d_ar_seq.h) + // drain 4, tests only (R4D_AR_TEST_LATE_PUSH, r4d_selftest): the flag goes out before the push + // and the push ~20 us after it, so the peer sees a flag whose bytes have not landed -- what a + // push over PCIe P2P now and then does on its own -- on every launch. + if (drain == 4) { + if (tid == 0) store_sys_rel(&peer_flags[b], s); + const unsigned long long t0 = wall_clock64(); + while (wall_clock64() - t0 < 2000ull) __builtin_amdgcn_s_sleep(8); // 100 MHz: 20 us + } // Push the chunk to the peer slot, 4x unrolled for memory-level parallelism. { int k = start + tid; @@ -97,13 +106,13 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( // 3 = all-thread s_wait_storecnt 0: every wave drains its posted writes with no L2 // writeback-invalidate; PCIe keeps posted writes to one peer ordered, so the release flag // lands after the data. Correct only for fine-grained memory (coarse leaves data in L2). - r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s, drain == 4); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); if (tid == 0) { if (drain == 2) __threadfence_system(); - store_sys_rel(&peer_flags[b], s); + if (drain != 4) store_sys_rel(&peer_flags[b], s); unsigned long long z = 0; // A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes. while (r4d_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) { @@ -550,6 +559,9 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes + // Tests only: every push lands after its flag (drain 4 above). Not in the tuning table, so no + // tuner can pick it. + if (const char* e = std::getenv("R4D_AR_TEST_LATE_PUSH"); e && *e == '1') drain = 4; #define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<<>>( \ (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 49db426e..329e3714 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -23022,6 +23022,32 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector& devs, co if (row->fini) { row->fini(a.inst); row->fini(b.inst); } } +/* Every peer push landing after its flag (the kernel's test mode, R4D_AR_TEST_LATE_PUSH): a push + * over PCIe P2P sometimes lands a microsecond or more after the release flag that follows it, so a + * reader that trusted the flag would sum the slot's previous contents. The push check + * (r4d_ar_seq.h) makes the reader wait for the bytes; here every launch of the sweep needs it. */ +static void ar_two_rank_late(const Plugin& pl, const std::vector& devs, const char* name) { + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; } + setenv("R4D_AR_TEST_LATE_PUSH", "1", 1); + ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] }; + std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b); + ta.join(); + tb.join(); + unsetenv("R4D_AR_TEST_LATE_PUSH"); + ok("2-rank all-reduce init, pushes landing after their flags", + a.rc_init == RAD_OK && b.rc_init == RAD_OK, + "rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init)); + if (a.rc_init != RAD_OK || b.rc_init != RAD_OK) return; + ok("2-rank all-reduce, every push landing ~20 us after its flag, 32 rounds, every sum exact on " + "both ranks", + a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && a.bad == 0 && b.bad == 0, + "rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + ", " + + std::to_string(a.bad + b.bad) + " elements wrong"); + if (row->fini) { row->fini(a.inst); row->fini(b.inst); } +} + /* ------------------------------------------------------------------ the two-rank all-gather */ /* The payload is what the vocab-parallel sampler gathers: (u32 global token id, f32 logit) pairs. * A token id's bit pattern read as f32 is a denormal, so an all-gather emulated by an all-reduce @@ -28499,6 +28525,7 @@ static void device_phase(const Plugin& pl) { if (!std::strcmp(base, "ar_oneshot_2rank_exact")) { ar_two_rank(pl, devs, n.c_str()); ar_two_rank_sweep(pl, devs, n.c_str()); + ar_two_rank_late(pl, devs, n.c_str()); } else { gather_two_rank(pl, devs, n.c_str()); } From be85c0ba7fbad57648c58da54630be83d3b37117 Mon Sep 17 00:00:00 2001 From: mici81 Date: Wed, 21 Oct 2026 16:12:37 +0000 Subject: [PATCH 12/27] qwen35_fp8: weight reads beside the decode all-reduces, trunk and DFlash2 drafter As gemma4_bf16 does (prefetch_beside): at two or more ranks, on decode steps of up to 32 rows, gate_up's first 12 MB is read into the on-die cache beside the mixer's all-reduce and the next layer's first projection's beside the feed-forward's; the DFlash2 drafter's reads take the same 12 MB. Qwen3.8-27B MXFP4 + DFlash2, tp 2, 2x R9700: no speculation x1 61.2 -> 67.9 tok/s (+11 %), x4 225.0 -> 251.2 (+12 %), x8 403.7 -> 438.6 (+9 %), x16 650.8 -> 668.1 (+3 %), x32 +0.8 %; speculation 7 x1..x16 +0..+2 % for the trunk, the drafter's reads x1 +6 % (median of eight rounds); prefill unchanged. The size and ceiling sweep is in the comment by kPrefetchBytes. RADIANCE_PREFETCH=0 declares none: arch_test's pipe-off case now sets it and still meets the serial graph pinned before either existed. qwen35_w8a8 builds the same source; the routed (MoE) trunk takes no reads. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/qwen35_fp8/qwen35_fp8.cpp | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 25570fed..f341a5a4 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -106,11 +106,30 @@ using Ffn = MlpFP8; using MtpHead = MtpFP8; #endif +/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first + * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2 at tp 2 + * on 2x R9700 (Gen5 x8), one round each, no speculation, x1 / x4 / x8 / x16 tok/s against none + * (61.2 / 225.0 / 403.7 / 650.8): 8 MB 65.1 / 246.4 / 410.9 / 663.3; 10 MB 66.0 / 250.1 / 425.0 / + * 668.5; 12 MB 67.9 / 251.2 / 438.6 / 668.1; 14 MB 67.8 / 249.5 / 432.4 / 659.1; 16 MB 67.0 / 244.9 / + * 422.7 / 649.4; 20 MB 63.4 / 232.0 / 408.1 / 630.7; 32 MB 57.9 / 210.2 / 372.8 / 605.9 -- past + * ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it should feed. Reads up + * to 128 rows: x32 963.8 against 956.0, x64 1206.7 against 1216.6, so the ceiling is 32 rows (a + * verify of four sequences at speculation 7). With speculation 7 (three rounds) x1..x16 +0.1..+1.9 %. + * The drafter's reads (Dflash2::Config::prefetch) take the same size: speculation 7, eight rounds, + * median x1 +6 %, x16 unchanged. */ +constexpr int64_t kPrefetchBytes = (int64_t)12 << 20; +constexpr int64_t kPrefetchStepRows = 32; + struct Layer { int full = 0; AttnGatedFP8 attn; GdnFP8 gdn; Ffn mlp; + /* The reads beside the decode all-reduces (prefetch_beside, rad_arch.h): gate_up's leading + * bytes beside the mixer's reduction, the next layer's first projection's beside the + * feed-forward's. 0 where none is declared. */ + rad_op op_pf_gu = 0, op_pf_next = 0; + rad_weight pf_gu_w = 0, pf_next_w = 0; }; struct Model { @@ -283,6 +302,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui Dflash2::Config dc{}; dc.short_block = 1; /* rad_drafter_short_block below */ + dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -1026,6 +1046,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp; #endif +#if !QWEN35_MOE + /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). At decode + * heights each block's reduction leaves the card's memory idle for its round trip over the link, + * so the GEMM behind it has its weight's leading bytes read into the on-die cache there: gate_up + * behind the mixer's reduction, the next layer's first projection (the delta net's in-projection, + * an attention layer's q|gate) behind the feed-forward's. Only at more than one rank; + * RADIANCE_PREFETCH=0 declares none (decl_prefetch). */ + if (g.world > 1 && rad_op_declared(b, "prefetch")) { + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.pf_gu_w = lay.mlp.gate_up.w; + lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes); + if (l + 1 < m.n_main) { + const Layer& nx = m.layers[(size_t)l + 1]; + lay.pf_next_w = nx.full ? nx.attn.qg.w : nx.gdn.in.w; + lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes); + } + } + } +#endif + m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)), @@ -1497,12 +1538,19 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok, rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs)); + /* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a + * step that carries a prompt's rows. This ceiling, not prefetch_beside's own (16), decides: it + * is passed a height of 1 where the step qualifies. */ + const int64_t pf_h = + batch->phase == RAD_PHASE_DECODE && batch->n_tok <= kPrefetchStepRows ? 1 : INT64_MAX; for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) { const Layer& l = m.layers[(size_t)li]; if (l.full) l.attn.step(c, batch); else l.gdn.step(c, batch); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x); l.mlp.step(c, batch); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x); /* The tap, after the layer: the drafter conditions on this layer's output, which the next From c9f79c32d8bbacbd1f38b5c0418ff16408b724c5 Mon Sep 17 00:00:00 2001 From: mici81 Date: Thu, 22 Oct 2026 15:51:58 +0000 Subject: [PATCH 13/27] gemma3: weight reads beside the decode all-reduces, trunk and DFlash2 drafter As qwen35_fp8 has them (prefetch_beside, rad_arch.h): behind the o GEMM, beside the attention block's all-reduce, gate|up's leading 24 MB are read into the on-die cache; behind the down GEMM, beside the feed-forward's, the next layer's q; the drafter's all-reduces take the same (Dflash2::Config::prefetch). Decode steps of up to 32 rows, none on a step with a prompt's rows, only at more than one rank; RADIANCE_PREFETCH=0 declares none. TranslateGemma-27B MXFP4 + DFlash2, TP2 on two R9700s, no speculation, two rounds, x1 / x4 / x8 tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 / 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9; 16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4; 24 MB 64.4 / 206.4 / 359.3 (+13.4 / +13.4 / +10.5 %); 32 MB 63.1 / 201.4 / 351.9. With speculation 7 (three rounds, greedy, medians) x1 / x4 / x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6 (+12.1 / +4.7 / 0.0 / +1.0 %). Bit for bit: a prefetch reads weights only. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/gemma3/gemma3.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index deb2d3fb..cec5d9b7 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -914,12 +914,28 @@ struct G3JunctionFP8 { } }; +/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first + * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows (a verify of four sequences at + * speculation 7, as qwen35_fp8's). TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (Gen5 x8), + * no speculation, two rounds each, x1 / x4 / x8 tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 / + * 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9; 16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4; + * 24 MB 64.4 / 206.4 / 359.3; 32 MB 63.1 / 201.4 / 351.9. Larger than qwen35_fp8's 12 MB: this + * model's hidden width (5376) and weights are larger, so its all-reduces take longer and its GEMMs + * read more; past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it should + * feed. With speculation 7 (three rounds, greedy, medians) x1 / x4 / x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6. The drafter's reads (Dflash2::Config::prefetch) take the same size. */ +constexpr int64_t kPrefetchBytes = (int64_t)24 << 20; +constexpr int64_t kPrefetchStepRows = 32; + struct Layer { bool global = false; Gemma3Attn attn{}; Gemma3Mlp mlp{}; G3Junction j_am{}, j_ma{}; G3JunctionFP8 jf_am{}, jf_ma{}; + /* The reads beside the decode all-reduces: gate|up's leading bytes beside the attention block's + * reduction, the next layer's q's beside the feed-forward's. 0 where none is declared. */ + rad_op op_pf_gu = 0, op_pf_next = 0; + rad_weight pf_gu_w = 0, pf_next_w = 0; }; struct Model { @@ -1004,6 +1020,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui Dflash2::Config dc{}; dc.short_block = 1; /* rad_drafter_short_block below */ + dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -1355,6 +1372,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } m.fuse_mx_ar = ar; } + /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). Only at + * more than one rank; RADIANCE_PREFETCH=0 declares none (decl_prefetch). */ + if (g.world > 1 && rad_op_declared(b, "prefetch")) { + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.pf_gu_w = lay.mlp.ln_gu.w; + lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes); + if (l + 1 < g.n_layer) { + lay.pf_next_w = m.layers[(size_t)l + 1].attn.ln_q.w; + lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes); + } + } + } /* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */ if (m.pipe_on) { bool ok = m.fuse_mx; @@ -1672,6 +1702,9 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE); + /* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a + * step that carries a prompt's rows (as qwen35_fp8's). */ + const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= kPrefetchStepRows ? 1 : INT64_MAX; if (m.fuse_mx) { /* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction; * the last block's tail runs unfused into the final norm. */ @@ -1682,9 +1715,11 @@ static void step(RadCtx* c, const RadBatch* batch) { /* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */ const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T); l.attn.step(c, batch, true, true, far); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (!far) l.attn.post(c, T); l.jf_am.step(c, T, far); l.mlp.step(c, batch, true, !last, far); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (!last) { if (!far) l.mlp.post(c, T); l.jf_ma.step(c, T, far); @@ -1698,8 +1733,10 @@ static void step(RadCtx* c, const RadBatch* batch) { const bool last = li + 1 == m.layers.size(); const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */ l.attn.step(c, batch, m.fuse, m.fuse, ar); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (m.fuse) l.j_am.step(c, T, ar); l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (m.fuse && !last) l.j_ma.step(c, T, ar); tap(li); } From de53cd18c125311be5a0db5bc92a12942b6a5f95 Mon Sep 17 00:00:00 2001 From: mici81 Date: Wed, 21 Oct 2026 16:12:37 +0000 Subject: [PATCH 14/27] runtime: an op that names no buffer is not held to the second lane's window The window keeps lane 1's concurrent buffers live only across it. A weight read into the cache (prefetch_beside) names no buffer, so it touches nothing the window protects: it may run on lane 1 outside the window (a DFlash2 drafter's reads come after the trunk's window), and it leaves no window work for lane 0 to join. runtime_test covers it. Co-Authored-By: Claude Opus 5.5 (1M context) --- core/runtime/issue.cpp | 10 +++++++--- tests/runtime_test.cpp | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 5baf187c..154f12b3 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -595,8 +595,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { : "has no device kernel for this band"); /* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across * it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside - * it, on either side: a transient of such an op may share bytes with a concurrent buffer. */ - if (program_ && program_->lane1_w1 >= 0) { + * it, on either side: a transient of such an op may share bytes with a concurrent buffer. An op + * that names no buffer (a weight read into the cache, prefetch_beside) touches nothing the window + * keeps live and has no transient: it runs on lane 1 anywhere and leaves no window work to join. */ + bool names_buf = false; + for (int i = 0; i < n_opd && !names_buf; ++i) names_buf = opd[i].kind == RAD_OPK_BUF; + if (program_ && program_->lane1_w1 >= 0 && names_buf) { const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1; if (lane_ == 1 && outside) return abort_step_msg(h, RAD_E_STATE, @@ -610,7 +614,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { return abort_step_msg(h, js, "joining the second lane outside its window failed"); } } - if (lane_ == 1) lane1_pending_ = true; + if (lane_ == 1 && names_buf) lane1_pending_ = true; /* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */ if (ip.ranged_div > 1 && n % ip.ranged_div != 0) diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index f87129c9..c01dddf9 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -993,6 +993,26 @@ TEST(an_op_outside_the_window_on_lane_0_joins_the_second_lane_first) { })); } +/* An op that names no buffer -- a weight read into the cache (prefetch_beside) -- touches nothing the + * window keeps live, so on lane 1 it runs outside the window too (a drafter's reads beside its + * all-reduces come after the trunk's window). */ +TEST(an_op_naming_no_buffer_runs_on_the_second_lane_outside_its_window) { + Fixture f; + f.P.scratch_regions = 2; + rad_weight w = f.add_weight("blk.0.w", RAD_BF16, 8, 4, g_weight_bytes); + rad_op a0 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen0 }, { "s0" }, nullptr, {}); + rad_op a1 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen1 }, { "s1" }, nullptr, { w }); + f.P.lane1_w0 = f.P.lane1_w1 = (int32_t)a0; + CHECK_OK(f.start()); + + CHECK_OK(f.step(4, 0, [&](Ctx& c) { + RadOperand opd[1] = { RAD_W(w) }; + CHECK_OK(c.set_lane(1)); + CHECK_OK(c.issue(a1, opd, 1, RAD_N_BATCH)); + CHECK_OK(c.set_lane(0)); + })); +} + /* Operands are positional (spec §2.3), so a miscount is silent numerical garbage at the kernel, * not a diagnosable failure. The runtime checks the given arity against the schema. */ TEST(operand_arity_is_checked_against_the_schema) { From 8998349eec9ec8334c0f599ca5972ea81aa55f24 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sat, 24 Oct 2026 12:43:19 +0000 Subject: [PATCH 15/27] qwen35_fp8, gemma3: the weight reads beside the all-reduces are switched off by RADIANCE_PREFETCH_BESIDE=0 1.12.0 dropped RADIANCE_PREFETCH; the reads are now issued, or not, by prefetch_beside's own switch. Co-Authored-By: Claude Opus 5.5 (1M context) --- arch/gemma3/gemma3.cpp | 2 +- arch/qwen35_fp8/qwen35_fp8.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index cec5d9b7..35164a5b 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -1373,7 +1373,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.fuse_mx_ar = ar; } /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). Only at - * more than one rank; RADIANCE_PREFETCH=0 declares none (decl_prefetch). */ + * more than one rank; RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ if (g.world > 1 && rad_op_declared(b, "prefetch")) { for (int64_t l = 0; l < g.n_layer; ++l) { Layer& lay = m.layers[(size_t)l]; diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index f341a5a4..4700ad48 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -1052,7 +1052,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * so the GEMM behind it has its weight's leading bytes read into the on-die cache there: gate_up * behind the mixer's reduction, the next layer's first projection (the delta net's in-projection, * an attention layer's q|gate) behind the feed-forward's. Only at more than one rank; - * RADIANCE_PREFETCH=0 declares none (decl_prefetch). */ + * RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ if (g.world > 1 && rad_op_declared(b, "prefetch")) { for (int64_t l = 0; l < m.n_main; ++l) { Layer& lay = m.layers[(size_t)l]; From bc272f897dcd140f12de5097c296f4766aa7c5c5 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 25 Oct 2026 07:52:37 +0000 Subject: [PATCH 16/27] arch_test: the pins of the families this branch changes, on the new base Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/arch_test.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 6ca1bcbe..223ba77e 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -8629,7 +8629,7 @@ struct ArchCases { qwen35_fp8::step, 3, {}, 0x74fd4495028c1525ull); add("qwen35_fp8 + MTP, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 3); return qwen35_fp8::declare(b, q35.meta(), &c); }, - nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x1c28909125c12f52ull); + nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x7c11e3c8243c955full); add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); }, qwen35_fp8::step, 7, {}, 0x5eaef1ee37575caeull); @@ -8638,7 +8638,7 @@ struct ArchCases { qwen35_w8a8::step, 7, {}, 0x5a4f256c6fda0e87ull); add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xb825b9d264795b8eull); + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xdc5540151b0d6684ull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); @@ -9339,7 +9339,7 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { { "qwen4exp_fp8", 4, 0, 0x1e97a26b759d29dfull, 0xfbe74f2b9d7020bfull }, { "qwen4exp_fp8", 4, 3, 0x6669aa0573931943ull, 0x36df57cac613c6cfull }, { "qwen35_fp8", 1, 0, 0xcfc82ca915ec549dull, 0x4d6fca823d1e97efull }, - { "qwen35_fp8", 2, 1, 0x5085b8c443c59f7cull, 0xb297654cef04bf08ull }, + { "qwen35_fp8", 2, 1, 0xcaf28466af9e917dull, 0x0bcf5833fce11a86ull }, { "qwen35moe_fp8", 1, 0, 0x7fa7b015e1bc8873ull, 0x3fcf71676e558d79ull }, { "qwen35moe_fp8", 2, 0, 0xf60c9508dd197370ull, 0x05e0778848bf416cull }, }; From 2af10794154c493d027becc175ecad2d14e5d74b Mon Sep 17 00:00:00 2001 From: mici81 Date: Sat, 24 Oct 2026 15:34:21 +0000 Subject: [PATCH 17/27] libr4d: the head-256 split-KV decode attention aims at 256 workgroups at one or two waves At one or two waves a workgroup (q_len * gqa <= 32: a plain decode step, or the DFlash2 short block's 4-row verify) the 128-workgroup target leaves too few KV bytes in flight for the card's DRAM; twice as many workgroups reach it. At three waves (an 8-row verify) more workgroups only add contention, so those keep 128. Qwen3.8-27B MXFP4 at TP2 on 2x R9700, k6_v4 KV: - r4d_selftest --perfdecattn: 4 sequences x 1 row over 100k 582 -> 464 us, 1 x 1 over 100k 264 -> 175, 16 x 4 rows over 41k 985 -> 801; 4 x 8 rows over 100k +9 % (kept at 128). - The server's decode step at speculation 7 (the median gap between steps carrying every sequence, three rounds): 8 x 41k 34.01 -> 32.48 ms (-4.5 %), 16 x 25k 44.65 -> 43.19 ms (-3.3 %). The split count already moves with the batch (8 sequences at 256 split as 4 do at 128), so the merge sees no new partition; not bit-identical to the 128 target at the same batch. Co-Authored-By: Claude Opus 5.5 (1M context) --- libr4d/r4d_attn_decode_h256_gqa6.hip | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 90851dc5..ccbeb03b 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -958,11 +958,23 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile, // head_dim f16, written once and read once): at eight requests 12.8 MB at splits 32 vs 3.2 MB at // 8, 19% of a 16K step's KV but 1.2% at 128K. The effect fades with depth, never enough to need a // context term. +// +// The target is 256 workgroups where a workgroup has one or two waves (q_len * gqa <= 32: a plain decode, +// or a 4-row verify of the DFlash2 short block), 128 otherwise. A one- or two-wave workgroup keeps too +// few KV bytes in flight for the card's DRAM at 128 (about one a CU); twice as many reach it. Qwen3.8-27B +// at TP2 on the R9700, k6_v4: r4d_selftest --perfdecattn (2 rounds) 4 x 1 row over 100k 582 -> 464 us, +// 1 x 1 row over 100k 264 -> 175, 16 x 4 rows over 41k 985 -> 801 (x4 and x8 the target were worse +// than x2); the server's decode step at speculation 7 (three rounds, medians, the steps carrying every +// sequence) 8 x 41k 34.01 -> 32.48 ms, 16 x 25k 44.65 -> 43.19. At three waves (an 8-row verify) more +// workgroups only add contention: 4 x 8 rows over 100k +9 % at x2, so those keep 128. The split +// count already moves with the batch (8 sequences at 256 split like 4 at 128), so this adds no +// partition the merge did not already see. static inline int r4d_decode_splits(const R4DArgs* a, int tile) { if (a->splits > 0) return a->splits; const int tiles = (a->max_ctx + tile - 1) / tile; const int units = std::max(1, a->kv_heads * a->num_seqs); - int s = 128 / units; + const int gqa = a->kv_heads > 0 ? std::max(1, a->q_heads / a->kv_heads) : 1; + int s = (a->q_len * gqa <= 32 ? 256 : 128) / units; const int cap = tiles / 2; if (s > cap) s = cap; if (s > tiles) s = tiles; From d0c44cf5a3d5b1ec3ff5e03e233fad9e29e521e2 Mon Sep 17 00:00:00 2001 From: dustin Date: Fri, 23 Oct 2026 10:11:57 -0500 Subject: [PATCH 18/27] tools: a w2a8 recipe in the fallback shape table -- rad-tune can now size the draft head it serves rad-tune skips a (kernel, shape) pair it cannot size: a schema names operands, not extents, and a tool has to allocate the bytes the kernel will read. For gemm_nt_q the reference describes the fp8 and the symmetric integer grids and declines every grid with a zero point, because ref_planes.h joins scale and zero into one operand a RadOpdDesc cannot state. w2a8 is such a grid, and it is the one the DFlash2 draft head serves, so both of its bands were skipped at every tune and the served card ran the axis defaults for them. The extents are not a guess. r4d_rad_layout_w2a8 owns them: codes to fragment order, N*K/4 bytes (r4d.w2a8.frag.g128), and one dword per row and 128 of K joining that group's f16 scale and integer zero, tile-major, N*K/128 of them (r4d.w2a8.sz.g128). The activation triple is quant_act_i8's own output -- int8 codes, one f32 scale a row, and the group-major code sums with rows padded to 16 -- and the grid is asymmetric, so the kernel refuses the case without the sums. b_ref stays absent; the reference exponent is mxfp4's. relayout_parity_test is where both sides exist, so the claim goes there: the table's byte total for b and b_scale against the same hooks' RadLayout.bytes, over libquant's planes, for w2a8 and for mxfp4a8, whose sizes the table has carried untested since it was written. Writing the table's K/4 as K/2 fails it with "the table sizes 32768 byte(s), the kernel stores 16384". The kernel's own guards -- K a whole number of 128-column blocks, N a whole number of 16-row tiles, the group the stored form has -- are pinned as refusals, and the shape a two-rank draft head tunes at (M 8, N 124160, K 2560, group 128) is pinned as accepted. --- tests/CMakeLists.txt | 6 +++ tests/relayout_parity_test.cpp | 86 +++++++++++++++++++++++++++++++++- tools/opshapes.cpp | 32 +++++++++++-- 3 files changed, 118 insertions(+), 6 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cb1e974a..91c97a2e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -176,6 +176,12 @@ foreach(t ${RAD_TESTS}) target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS}) target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d) target_compile_options(${n} PRIVATE -ffp-contract=off) + # relayout_parity_test also holds tools/opshapes.cpp's fallback table to these hooks' byte + # totals, so it needs the table's source too. + if(n STREQUAL relayout_parity_test) + target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools/opshapes.cpp) + target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools) + endif() elseif(n IN_LIST RAD_TESTS_WHOLE_CORE) add_executable(${n} ${t}) target_link_libraries(${n} PRIVATE stdc++ "$") diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index 427a428f..b5a3a364 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -9,10 +9,13 @@ * see. Where the kernel has an inverse, it must give the planes back exactly. * * libr4d needs a HIP toolchain to build but its layouts do not, so their host sources are compiled - * into this test (tests/CMakeLists.txt). The n-gram table's hook is libavx's, from the plugin. + * into this test (tests/CMakeLists.txt). The n-gram table's hook is libavx's, from the plugin. One + * test here therefore reaches back into tools/opshapes.cpp: the fallback table sizes the packed + * weights these hooks own, and only this file can hold both sides of that claim. */ #include "quant_fixture.h" #include "r4d_plugin.h" +#include "opshapes.h" #include #include @@ -346,6 +349,87 @@ TEST(mxfp4_codes_exponents_and_the_row_reference) { 0xc35d26b146836d77ull); } +/* tools/opshapes.cpp sizes a packed weight from the kernel's stored form, because no schema states + * an extent and libref declines every grid with a zero point (ref_planes.h joins scale and zero + * into one operand a description cannot state). A stale entry is not a failed check: rad-tune + * allocates what the table says and hands the kernel the short buffer, which is a read past the + * allocation on the card, not a refusal. So the table's byte total and the hook's `bytes` must + * agree. The table's shapes are the tool's own view -- mxfp4's exponents are [K/32][N] there and + * [N][K/32] in the store -- so the totals, not the shapes, are the contract. */ +TEST(the_tool_table_sizes_packed_weights_as_the_kernel_stores_them) { + NEED_LIBQUANT(); + const int64_t N = 128, K = 512, M = 8; + auto check = [&](const char* dtype, int64_t group, const Hooks& hk, + const std::vector& bscale_roles, Opts qo) { + const std::vector w = weight(N, K, 21, 1, group); + const Quantised q = quantise(quantizer("rtn"), qo, "output.weight", N, K, w); + if (q.status != RAD_OK) { + CHECK_EQ(q.status, RAD_OK); + return; + } + Opts kp; + kp.i("N", N).i("K", K); + rad::Geometry g; + g.set_i("M", M); g.set_i("N", N); g.set_i("K", K); g.set_i("group", group); + g.set_s("dtype", dtype); + std::vector tab; + if (rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab) != RAD_OK) { + std::fprintf(stderr, " %s: the table refuses the geometry\n", dtype); + CHECK(false); + return; + } + CHECK_EQ((int)tab.size(), 7); + struct P { int operand; size_t opd; std::vector roles; }; + const std::vector

ops = { { B, 2, { "codes" } }, { BSCALE, 3, bscale_roles } }; + for (const P& o : ops) { + const Selection s = select(q, N, K, o.roles); + RadLayout L{}; + CHECK_EQ(hk.layout(kp.data(), kp.n(), o.operand, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), &L), RAD_OK); + const rad::OpdShape& t = tab[o.opd]; + const int64_t got = t.absent ? 0 : rad_dtype_bytes(t.dtype, rad::rad_numel(t.shape)); + if (got != (int64_t)L.bytes) + std::fprintf(stderr, " %s operand %d: the table sizes %lld byte(s), the kernel " + "stores %lld\n", dtype, o.operand, (long long)got, + (long long)L.bytes); + CHECK_EQ(got, (int64_t)L.bytes); + } + }; + { + Opts qo; + qo.s("codes", "u2").s("zero", "u8").i("group", 128).s("scale", "f16"); + check("w2a8", 128, nW2, { "scale", "zero" }, qo); + } + { + Opts qo; + qo.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0"); + check("mxfp4a8", 32, nMx, { "scale" }, qo); + } + /* The guards are the kernel's own: K a whole number of 128-column blocks + * (r4d_layout.cpp refuses a weight whose K is not), N a whole number of 16-row tiles (the + * row's constraint), and the group the stored form has. A geometry the kernel would refuse has + * to be refused here too, or rad-tune would size buffers for a launch that never happens. */ + auto refuses = [&](int64_t n, int64_t k, int64_t group) { + rad::Geometry g; + g.set_i("M", M); g.set_i("N", n); g.set_i("K", k); g.set_i("group", group); + g.set_s("dtype", "w2a8"); + std::vector tab; + CHECK_EQ(rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab), RAD_E_UNSUPPORTED); + }; + refuses(128, 500, 128); /* K leaves a partial block */ + refuses(120, 512, 128); /* N leaves a partial tile */ + refuses(128, 512, 64); /* a group the stored form does not have */ + /* The shape the DFlash2 draft head tunes at on a two-rank serve, which the kernel takes. */ + { + rad::Geometry g; + g.set_i("M", M); g.set_i("N", 124160); g.set_i("K", 2560); g.set_i("group", 128); + g.set_s("dtype", "w2a8"); + std::vector tab; + CHECK_EQ(rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab), RAD_OK); + CHECK_EQ((int)tab.size(), 7); + } +} + TEST(moe_int4_experts_plain_and_rotated_both_classes) { NEED_LIBQUANT(); const int64_t N = 64, K = 256, N1 = 48, K1 = 128; diff --git a/tools/opshapes.cpp b/tools/opshapes.cpp index 72769ed7..32953917 100644 --- a/tools/opshapes.cpp +++ b/tools/opshapes.cpp @@ -154,11 +154,15 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6 add((uint32_t)RAD_F32, {M, (n + group - 1) / group}); } else if (op == "gemm_nt_q") { - /* Block-scaled fp8 and mxfp4 only. `gemm_nt_q` covers six weight formats whose scale grids - * (per row, per row-group, per output-row-block, e8m0 exponents, zero points, reference - * exponents) belong to the reading kernel, not the schema. The fp8 grid is fixed by the - * checkpoint: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] scale plane, `group` - * being the 128. Other formats are skipped and counted. + /* Block-scaled fp8, mxfp4 and the 2-bit asymmetric grid. `gemm_nt_q` covers six weight + * formats whose scale grids (per row, per row-group, per output-row-block, e8m0 exponents, + * zero points, reference exponents) belong to the reading kernel, not the schema. The fp8 + * grid is fixed by the checkpoint: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] + * scale plane, `group` being the 128. libref describes the symmetric integer grids, so a + * tool takes those from its hook and never reaches this table for them; every grid with a + * zero point is declined there (ref_planes.h joins scale and zero into one operand a + * description cannot state), and the ones named here are sized from the kernel's own + * stored layout instead. Anything else is skipped and counted. * * `a_sum` and `b_ref` belong to the asymmetric-integer and mxfp4 grids. */ const char* q = g.get_s("dtype"); @@ -175,6 +179,24 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6 add((uint32_t)RAD_BF16, {M, N}); /* y */ skip_opd(); /* a_sum */ add((uint32_t)RAD_U8, {N}); /* b_ref -- the per-row reference */ + } else if (q && std::strcmp(q, "w2a8") == 0) { + /* The DFlash2 draft head's grid (libr4d/r4d_gemm_w2a8_nt.hip): unsigned 2-bit codes in + * the kernel's fragment order, N*K/4 bytes (`r4d.w2a8.frag.g128`), and one dword per + * row and `group` of K holding that group's f16 scale and integer zero, tile-major, + * N*K/group of them (`r4d.w2a8.sz.g128`) -- both extents owned by + * libr4d/r4d_layout.cpp's r4d_rad_layout_w2a8, which is what sizes the real weight. + * The activation pair and the group sums are quant_act_i8's own outputs above, and the + * grid is asymmetric, so the kernel refuses the case without `a_sum`. `b_ref` is + * mxfp4's. Sizes are the stored bytes; random bytes suffice for timing. */ + if (N <= 0 || K <= 0 || group != 128 || (K % 128) || (N % 16)) + return RAD_E_UNSUPPORTED; + add((uint32_t)RAD_I8, {M, K}); /* a -- int8 codes */ + add((uint32_t)RAD_F32, {M, 1}); /* a_scale -- one f32 per row */ + add((uint32_t)RAD_U8, {N, K / 4}); /* b -- u2 codes, fragment order */ + add((uint32_t)RAD_U32, {N, K / group}); /* b_scale -- scale+zero dwords */ + add((uint32_t)RAD_BF16, {M, N}); /* y */ + add((uint32_t)RAD_F32, {K / group, (M + 15) / 16 * 16}); /* a_sum, group-major */ + skip_opd(); /* b_ref */ } else { const bool a8 = q && std::strcmp(q, "fp8a8") == 0; const bool a16 = q && std::strcmp(q, "fp8a16") == 0; From e9555d2bc149aade5737a2a17cb6b37540f3a44a Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 13:40:26 -0500 Subject: [PATCH 19/27] tune: measure collectives as the exchange -- per-rank operands and instances, device.p2p measured before declare, tune requests carrying their instance --- abi/rad_device.h | 5 + core/build/rad_build.h | 1 + core/build/rad_builder.cpp | 25 +++ core/device/dispatch.cpp | 1 + core/rad_core.h | 7 + docs/TOOLS.md | 10 + tools/rad_tune.cpp | 391 +++++++++++++++++++++++++++---------- 7 files changed, 339 insertions(+), 101 deletions(-) diff --git a/abi/rad_device.h b/abi/rad_device.h index 0bfbfa59..72a12511 100644 --- a/abi/rad_device.h +++ b/abi/rad_device.h @@ -42,6 +42,11 @@ int rad_dev_count(void); int rad_dev_set(int device); int rad_dev_props(int device, RadDeviceProps* out); int rad_dev_enable_peer(int self, int peer); +/* Whether the driver reports that `self` can reach `peer`'s memory, 1 or 0, asked before anything + * is enabled: this is the fact collectives constrain (rad_types.h's RAD_FACT_P2P), so a tool that + * declares a multi-rank graph must measure it and set the fact as Engine does. Negative on a + * device error. */ +int rad_dev_peer_access(int self, int peer); void* rad_dev_alloc(int64_t bytes, int kind); void rad_dev_free(void* p, int kind); diff --git a/core/build/rad_build.h b/core/build/rad_build.h index e606e7e1..ae7d954c 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -197,6 +197,7 @@ private: /* init() for every surviving instance, after the whole graph has resolved, so a failing init * cannot abort declare before the miss report is assembled. */ void finish_instances(); + void fill_tune_instances(); int32_t find_kv_consumer(rad_kvgroup g); void finish_layouts(); void finish_kv_groups(); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 2fa9d950..ad8c7f8e 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -487,6 +487,7 @@ void Builder::record_tune_request(const Resolved& r) { req.geom = r.geom; req.geom_key = r.geom_key; req.info = r.row->info; + req.instance = r.instance; prog_.tune_requests.push_back(std::move(req)); } @@ -597,6 +598,29 @@ void Builder::finish_instances() { } } } + +/* The instances are made in finish_instances(), after record_tune_request ran, so the requests + * now carry the instance their kernel will launch with. A collective's launch cannot be formed + * without it -- the peer bundle (scratch, flags, sequence counters) is what init() builds and + * RadArgs reaches the exchange through nothing else -- so the tuner forms its launches from this. + * Keyed exactly as record_tune_request keyed. */ +void Builder::fill_tune_instances() { + for (size_t i = 1; i < prog_.ops.size(); ++i) { + const OpInfo& oi = prog_.ops[i]; + for (const Band& b : oi.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + const Resolved& r = b.dom[d]; + if (!r || !r.row || !r.row->info) continue; + const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin + + std::string("\x1f") + r.geom_key; + for (auto& t : prog_.tune_requests) + if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + + t.geom_key == key) + t.instance = r.instance; + } + } +} + rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, const rad_weight* w, int n_w) { if (finished_) return err(RAD_E_STATE, "decl_op('%s') after declare finished", opname ? opname : ""); @@ -2380,6 +2404,7 @@ int Builder::finish() { } if (instances_) finish_instances(); + fill_tune_instances(); finish_weight_uses(); finish_layouts(); finish_kv_groups(); diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 16b20d6f..8855e3f9 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -535,6 +535,7 @@ int dev_code_runs(size_t from, size_t to, int device, std::string* why) { extern "C" { +int rad_dev_peer_access(int self, int peer) { return rad::dev_peer_access(self, peer); } int rad_event_create_as(RadEvent* out, unsigned flags) { const int s = dev()->event_create(out, flags); diff --git a/core/rad_core.h b/core/rad_core.h index 8b6021e9..dd5fb92c 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -504,6 +504,13 @@ public: Geometry geom; std::string geom_key; const RadKernelInfo* info = nullptr; + /* The instance init() produced for this instantiation, null for a kernel with no init. + * A collective's launch cannot be formed without it: the peer bundle -- the scratch, the + * flags and the sequence counters, published to every rank and made peer-accessible at + * init -- is what makes the exchange addressable, and RadArgs carries no other route to + * it. The instance belongs to the rank this Program was declared for (Program::ctx), and + * the Registry that made it must outlive the launch (spec §1, §15). */ + void* instance = nullptr; }; std::vector tune_requests; diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 9948ea40..08d11452 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -655,6 +655,16 @@ Declare at the shapes you serve: At `--tp > 1` every rank declares at once, each on its own thread and device, as the engine does: a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 hangs. +A collective is then measured as the exchange, not as one rank's copy of it. Each rank gets its own +operands -- drawn with its own seed, so a fold of two identical halves cannot pass a correctness +check -- its own scratch, its own stream, and the instance its own declare made: `init` is what +publishes the peer bundle (scratch, flags, sequence counters) and a launch with no instance is +refused before it starts. The candidate's launches are fired on every rank at once and the clock +stops when the last stream drains, so the reported time is the round trip through the peer, which +is what the served step pays; timing rank 0 alone would time a local copy. Candidates are still +judged against the defaults on rank 0's output. A row that is not collective runs on rank 0 alone, +as it always did. + Before trusting a cache, check that the tuned variants beat the defaults. `RADIANCE_TUNE` pins a kernel's axes for such a comparison; it is a measurement aid, not a deployment setting. diff --git a/tools/rad_tune.cpp b/tools/rad_tune.cpp index f478b47f..d74bf679 100644 --- a/tools/rad_tune.cpp +++ b/tools/rad_tune.cpp @@ -55,9 +55,16 @@ void usage() { " -h, --help\n"); } -/* A device allocation that frees itself, because the timing path has several ways out. */ +/* A device allocation that frees itself, because the timing path has several ways out. Neither + * copyable nor movable: a rank holds a vector of these, and a second handle to the same + * allocation would free the buffer out from under a launch still reading it. */ struct DevBuf { void* p = nullptr; + DevBuf() = default; + DevBuf(const DevBuf&) = delete; + DevBuf& operator=(const DevBuf&) = delete; + DevBuf(DevBuf&&) = delete; + DevBuf& operator=(DevBuf&&) = delete; ~DevBuf() { if (p) rad_dev_free(p, RAD_MEM_DEVICE); } }; @@ -121,37 +128,120 @@ tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size, return out; } -/* Every OUT and INOUT operand's bytes after one launch at `g`, which carries the candidate point as - * ordinary parameters. Used to compare a candidate with the defaults. */ -int capture_outputs(const KernelRow& row, std::vector& t, - const Geometry& g, const RadOpSchema* schema, - const std::vector& sh, RadStream stream, - std::vector* out) { - RadArgs a{}; - a.t = t.data(); a.n_t = (int)t.size(); - a.p = g.params(); a.n_p = g.n_params(); - a.rank = 0; a.world_size = 1; - DevBuf scratch; - if (row.info->scratch) { - const int64_t need = row.info->scratch(&a); - if (need > 0) { - scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); - if (!scratch.p) return RAD_E_NOMEM; - rad_memset_async(scratch.p, 0, need, stream); - a.scratch = scratch.p; - a.scratch_bytes = need; - } - } - if (row.info->launch(&a, stream) < 0) return RAD_E_SHAPE; - if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE; +/* One rank's side of one candidate's launch: the instance declare made for it, the operands it + * owns on its own card, its scratch, and the stream it runs on. A row that is not a collective + * has exactly one of these, as an engine step's local op does. A collective has one per rank, and + * they are fired together: a rank that launches alone waits for a peer flag nobody raises. + * + * The instance is the reason this exists. init() is what builds the peer bundle -- the scratch and + * the flags and the sequence counters, published to every rank and made peer-accessible -- and + * RadArgs reaches the exchange through nothing else, so a tool that leaves it null cannot form a + * collective's launch at all. Every `ar_*` row used to end here that way: declared tunable + * (nblocks, nthreads, drain, acq), requested by the declared graph, and refused at the entry + * point before a single launch, so the served card ran the axis defaults for every all-reduce. */ +struct Rank { + int rank = 0, world = 1; + void* instance = nullptr; + RadStream stream = nullptr; /* owned by the request's StreamSet */ + std::vector t; /* the operands, as the kernel sees them */ + std::vector buf; /* ...and the allocations behind them */ + std::vector> host; /* the draw, only ever a copy source */ + DevBuf scratch; + int64_t scratch_bytes = 0; +}; +/* Streams die with the request, every way out of it, skips included. */ +struct StreamSet { + std::vector s; + ~StreamSet() { for (RadStream x : s) if (x) rad_stream_destroy(x); } +}; + +/* The RadArgs a rank's launch takes. The candidate's axes ride in `g` exactly as at issue, so the + * kernel reads `sk` with rad_args_geti() like `M`. */ +void fill_args(const KernelRow& row, Rank& r, const Geometry& g, RadArgs* a) { + std::memset(a, 0, sizeof(*a)); + a->t = r.t.data(); a->n_t = (int)r.t.size(); + a->p = g.params(); a->n_p = g.n_params(); + a->instance = r.instance; + a->rank = r.rank; + a->world_size = r.world; + if (r.scratch.p) { a->scratch = r.scratch.p; a->scratch_bytes = r.scratch_bytes; } +} + +/* Every rank's stream drained. A stream's device has to be current to sync it. */ +int sync_all(std::vector& rs) { + int st = RAD_OK; + for (Rank& r : rs) { + if (!r.stream) continue; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; + if (rad_stream_sync(r.stream) < 0) st = RAD_E_STATE; + } + return st; +} + +/* Scratch zeroed before a candidate starts, outside the timed region: a candidate must not be + * timed -- or judged -- on the leftovers of the one before it. */ +int zero_scratch(std::vector& rs) { + for (Rank& r : rs) { + if (!r.scratch.p) continue; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; + if (rad_memset_async(r.scratch.p, 0, (uint64_t)r.scratch_bytes, r.stream) < 0) + return RAD_E_STATE; + } + return RAD_OK; +} + +/* `iters` launches on every rank, from one thread each: the exchange only pipelines once both + * cards have work queued, so enqueuing rank 1's whole batch after rank 0's would charge every + * iteration for the enqueue of the batch, not just the first. + * + * A refusal comes back before anything is waited on. It is symmetric by construction -- every + * rank resolved the same kernel for the same geometry, and the launch's checks read only the + * geometry and the instance -- so a refusal means no rank queued work and there is nothing to + * drain. Were it ever asymmetric, the peers would be left spinning on a flag; that is why the + * caller treats any refusal as fatal for the candidate instead of retrying it. */ +int launch_all(const KernelRow& row, std::vector& rs, const Geometry& g, int iters) { + std::vector st(rs.size(), (int)RAD_E_STATE); + std::vector th; + th.reserve(rs.size()); + for (size_t i = 0; i < rs.size(); ++i) + th.emplace_back([&, i] { + Rank& r = rs[i]; + if (rad_dev_set(r.rank) < 0) { st[i] = RAD_E_DEVICE; return; } + RadArgs a; + fill_args(row, r, g, &a); + for (int k = 0; k < iters; ++k) { + const int s = row.info->launch(&a, r.stream); + if (s < 0) { st[i] = s; return; } + } + st[i] = RAD_OK; + }); + for (std::thread& t : th) t.join(); + for (int s : st) if (s < 0) return s; + return RAD_OK; +} + +/* Rank 0's OUT and INOUT bytes after one launch at `g`, which carries the candidate point as + * ordinary parameters. Every candidate saw the same bytes on every rank, so a variant that + * reorders a reduction, drops a peer's term, or writes the wrong slice differs from the defaults + * here. */ +int capture_outputs(const KernelRow& row, std::vector& rs, const Geometry& g, + const RadOpSchema* schema, const std::vector& sh, + std::vector* out) { + if (const int z = zero_scratch(rs)) return z; + const int w = launch_all(row, rs, g, 1); + if (w < 0) return w; + if (const int s = sync_all(rs)) return s; + + Rank& r = rs[0]; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; /* Size the destination before copying: growing it between async copies would reallocate it * under copies still in flight. */ size_t total = 0; for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) { const int role = schema->operands[k].role; if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue; - if (!t[k].data) continue; + if (!r.t[k].data) continue; const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); if (bytes > 0) total += (size_t)bytes; } @@ -160,13 +250,14 @@ int capture_outputs(const KernelRow& row, std::vector& t, for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) { const int role = schema->operands[k].role; if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue; - if (!t[k].data) continue; + if (!r.t[k].data) continue; const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); if (bytes <= 0) continue; - if (rad_memcpy_async(out->data() + at, t[k].data, bytes, stream) < 0) return RAD_E_STATE; + if (rad_memcpy_async(out->data() + at, r.t[k].data, bytes, r.stream) < 0) + return RAD_E_STATE; at += (size_t)bytes; } - if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE; + if (rad_stream_sync(r.stream) < 0) return RAD_E_STATE; return RAD_OK; } @@ -203,43 +294,30 @@ double max_rel_diff(const std::vector& a, const std::vector& b return worst; } -/* Median microseconds per launch at `g` (which carries the candidate point). Negative means the - * kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid prunes only - * what the geometry alone can rule out. */ -double time_point(const KernelRow& row, std::vector& t, - const Geometry& g, int reps, int iters, - RadStream stream, double* spread_pct) { - RadArgs a{}; - a.t = t.data(); a.n_t = (int)t.size(); - a.p = g.params(); a.n_p = g.n_params(); - a.rank = 0; a.world_size = 1; - /* Scratch must be device memory: e.g. a split-K GEMM writes its partial planes there. */ - DevBuf scratch; - if (row.info->scratch) { - const int64_t need = row.info->scratch(&a); - if (need > 0) { - scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); - if (!scratch.p) return (double)RAD_E_NOMEM; - rad_memset_async(scratch.p, 0, need, stream); - a.scratch = scratch.p; - a.scratch_bytes = need; - } - } +/* Median microseconds per iteration at `g` (which carries the candidate point): the wall time of + * `iters` launches on every rank, from the first launch to the last stream drained. Negative + * means the kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid + * prunes only what the geometry alone can rule out. + * + * The clock stops only after the devices finish: launches are asynchronous, so without the sync + * this would time host submission. For a collective that is doubly true -- the exchange's cost is + * the wait for the peer, and the wait happens on the card, so a rank timed alone would report a + * local copy. */ +double time_point(const KernelRow& row, std::vector& rs, const Geometry& g, + int reps, int iters, double* spread_pct) { + if (const int z = zero_scratch(rs)) return (double)z; /* A warm-up launch; its status decides whether this candidate serves the shape at all. */ - const int s = row.info->launch(&a, stream); - if (s < 0) return (double)s; - if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE; + const int w = launch_all(row, rs, g, 1); + if (w < 0) return (double)w; + if (const int s = sync_all(rs)) return (double)s; - /* Stop the clock only after the device finishes: launches are asynchronous, so without the - * sync this would time host submission only. */ std::vector us; us.reserve((size_t)reps); for (int r = 0; r < reps; ++r) { const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < iters; ++i) - if (row.info->launch(&a, stream) < 0) return (double)RAD_E_SHAPE; - if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE; + if (const int s = launch_all(row, rs, g, iters)) return (double)s; + if (const int s = sync_all(rs)) return (double)s; const auto t1 = std::chrono::steady_clock::now(); us.push_back(std::chrono::duration(t1 - t0).count() / iters); } @@ -337,12 +415,35 @@ int main(int argc, char** argv) { ctx.max_spec = spec >= 0 ? spec : probe.draft_depth; ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = ""; + /* Peer access, measured before selection, as Engine does: collectives constrain device.p2p + * (abi/rad_types.h), and with the fact unset neither the peer-to-peer row nor its host-memory + * twin can match, so every collective resolves to nothing -- silently, with no tune request + * for it ever reaching the loop below. Every ordered pair is asked, since access is granted + * one way at a time. */ + long long p2p = 1; + for (int i = 0; i < tp; ++i) + for (int j = 0; j < tp; ++j) { + if (i == j) continue; + const int a = rad_dev_peer_access(i, j); + if (a < 0) { + std::fprintf(stderr, "rad-tune: could not ask whether card %d can reach card %d's " + "memory: %s\n", i, j, rad_dev_last_error()); + return 1; + } + if (a == 0) p2p = 0; + } + rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p); + const char* p2p_note = p2p ? "peer to peer" : "the collectives run through pinned host memory"; + /* Every rank declares concurrently on its own thread and device, as Engine does: kernel init() - * runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for - * its peers), so declaring rank 0 alone would hang. Only rank 0's program is measured. */ - Program prog; + * runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for its + * peers), so declaring rank 0 alone would hang. + * + * All the programs stay alive, not only rank 0's. A collective's launch needs the instance each + * rank's own declare made, and an instance is reachable only through the program that declared + * it, so rank 0's program is the one measured while the others supply the peers. */ + std::vector progs((size_t)tp); { - std::vector progs((size_t)tp); std::vector st((size_t)tp, 0); std::vector th; for (int ri = 0; ri < tp; ++ri) { @@ -362,7 +463,16 @@ int main(int argc, char** argv) { for (auto& t : th) t.join(); if (tp > 1) rad_dev_set(0); for (int ri = 0; ri < tp; ++ri) if (st[(size_t)ri] < 0) return 1; - prog = std::move(progs[0]); + } + Program& prog = progs[0]; + + /* Name what resolved to nothing, so a hole is a printed line instead of a tune request that + * never appears: the engine's declare counts the misses, and this is the count's detail. */ + if (!prog.misses.empty()) { + RadDeviceProps dp{}; + const bool host_backend = rad_dev_props(0, &dp) >= 0 && dp.is_host_backend; + for (const Program::Miss* m : prog.device_holes(host_backend)) + std::printf(" unresolved %s\n", m->line().c_str()); } if (machine.empty()) machine = rad_machine_key(); @@ -378,6 +488,7 @@ int main(int argc, char** argv) { std::printf("rad-tune %s\n", model.c_str()); std::printf(" machine %s\n", machine.c_str()); + if (tp > 1) std::printf(" p2p %s\n", p2p_note); std::printf(" cache %s (%zu existing row(s))\n", src.c_str(), before); std::printf(" requests %zu (kernel, shape) pair(s) the declared graph reaches\n\n", prog.tune_requests.size()); @@ -393,14 +504,6 @@ int main(int argc, char** argv) { int measured = 0, skipped = 0, single = 0; std::map skip_why; - /* One explicit stream for the run; timing on the null stream would measure host submission. - * Without ROCm the device layer is a synchronous host stub, so the same path works. */ - RadStream stream = nullptr; - if (rad_stream_create(&stream, 0) < 0) { - std::fprintf(stderr, "rad-tune: could not create a stream: %s\n", rad_dev_last_error()); - return 1; - } - for (const Program::TuneRequest& tr : prog.tune_requests) { const KernelRow* row = row_for(tr.plugin, tr.kernel); if (!row || !row->info || !row->info->launch) { @@ -480,31 +583,118 @@ int main(int argc, char** argv) { } const int64_t vocab_rows = kf_vocab_rows(kop); - /* One set of device buffers shared by all candidates, so they all see the same bytes. - * `store` is the host-side draw, only ever a copy source; RadTensor::data must be the - * device allocation (a host address would fail silently). */ - std::vector> store(sh.size()); - std::vector dev(sh.size()); - std::vector t(sh.size()); + /* One set of operands per rank that takes part. A collective's ranks each contribute their + * own bytes on their own card -- peers write into each other's scratch, never into each + * other's input -- so rank 1's x has to be its own allocation, and each rank needs the + * instance its own declare made. Ranks draw different bytes on purpose: a fold of two + * identical halves would let a kernel that read its own contribution twice pass. + * + * `rs` is sized up front and never grown: DevBuf frees what it points at, so moving one + * into new storage would leave the old handle to free the buffer as well. */ + const int world = row->collective && tp > 1 ? tp : 1; + std::string scale; + if (world > 1) scale = ", " + std::to_string(world) + " ranks"; + std::vector rs((size_t)world); + StreamSet streams; bool ok = true; - for (size_t k = 0; k < sh.size() && ok; ++k) { - const int64_t n = rad_numel(sh[k].shape); - const int64_t bytes = rad_dtype_bytes(sh[k].dtype, n); - if (bytes <= 0) { ok = false; break; } - kf_draw(kop, k, M, vocab_rows, rad_case_seed(1, op, 0, row->info->domain, (int)k), - &store[k]); - dev[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE); - if (!dev[k].p) { ok = false; break; } - if (rad_memcpy_async(dev[k].p, store[k].data(), bytes, stream) < 0) { ok = false; break; } - t[k].data = dev[k].p; - t[k].dtype = sh[k].dtype; - t[k].rank = (uint32_t)sh[k].shape.size(); - for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d) - t[k].shape[d] = sh[k].shape[d]; - rad_tensor_pack(&t[k]); + for (int ri = 0; ri < world && ok; ++ri) { + Rank& r = rs[(size_t)ri]; + r.rank = ri; r.world = world; + /* The instance is found by the key the cache uses, not by position: a rank that + * resolved a different kernel for this band has no peer to exchange with. A + * collective cannot launch without it; a plain kernel has none, and null is exactly + * what its launch expects. */ + const Program::TuneRequest* q = &tr; + if (ri > 0) { + q = nullptr; + for (const auto& p : progs[(size_t)ri].tune_requests) + if (p.kernel == tr.kernel && p.plugin == tr.plugin && + p.geom_key == tr.geom_key) { q = &p; break; } + } + if (world > 1 && (!q || !q->instance)) { + skip_why[op + " (rank " + std::to_string(ri) + " declared no instance for this " + "instantiation: no exchange to launch)"]++; + ++skipped; ok = false; break; + } + r.instance = q ? q->instance : nullptr; + if (rad_dev_set(ri) < 0) { + skip_why[op + " (no device to put rank " + std::to_string(ri) + " on)"]++; + ++skipped; ok = false; break; + } + /* An explicit stream per rank; timing on the null stream would measure host + * submission. Without ROCm the device layer is a synchronous host stub, and the + * same path still works. */ + RadStream s = nullptr; + if (rad_stream_create(&s, 0) < 0) { + std::fprintf(stderr, "rad-tune: could not create a stream for rank %d: %s\n", ri, + rad_dev_last_error()); + return 1; + } + streams.s.push_back(s); + r.stream = s; + /* Inputs come from kf_draw, the same draw rad-kbench checks with, so each operand + * stays in the domain its recipe states (constant `seqused`, cumulative lengths, + * distinct scatter destinations, in-range block tables). */ + r.host.resize(sh.size()); + r.buf = std::vector(sh.size()); + r.t = std::vector(sh.size()); + for (size_t k = 0; k < sh.size(); ++k) { + /* An absent operand (attn's descales and cu_seqlens) is a zeroed tensor: no + * draw, no allocation, data null -- what kbench passes and the kernel checks. */ + if (sh[k].absent) continue; + const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); + if (bytes <= 0) { + skip_why[op + " (an operand has a plugin-private dtype the core cannot " + "size)"]++; + ++skipped; ok = false; break; + } + kf_draw(kop, k, M, vocab_rows, + rad_case_seed(1, op, ri, row->info->domain, (int)k), &r.host[k]); + r.buf[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE); + if (!r.buf[k].p) { + skip_why[op + " (no device memory for an operand on rank " + + std::to_string(ri) + ")"]++; + ++skipped; ok = false; break; + } + if (rad_memcpy_async(r.buf[k].p, r.host[k].data(), bytes, r.stream) < 0) { + skip_why[op + " (the operands would not copy onto rank " + + std::to_string(ri) + ")"]++; + ++skipped; ok = false; break; + } + /* RadTensor::data must be the device allocation; a host address fails silently. */ + RadTensor& t = r.t[k]; + t = RadTensor{}; + t.data = r.buf[k].p; + t.dtype = sh[k].dtype; + t.rank = (uint32_t)sh[k].shape.size(); + for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d) + t.shape[d] = sh[k].shape[d]; + rad_tensor_pack(&t); + } } - if (!ok) { skip_why[op + " (an operand has a plugin-private dtype the core cannot " - "size)"]++; ++skipped; continue; } + /* Scratch sized from each rank's own arguments: a split kernel writes its partials to + * device memory, and every card needs its own. */ + if (ok && row->info->scratch) { + for (Rank& r : rs) { + if (rad_dev_set(r.rank) < 0) { + skip_why[op + " (no device to size scratch on for rank " + + std::to_string(r.rank) + ")"]++; + ++skipped; ok = false; break; + } + RadArgs a; + fill_args(*row, r, tr.geom, &a); + const int64_t need = row->info->scratch(&a); + if (need <= 0) continue; + r.scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); + if (!r.scratch.p) { + skip_why[op + " (no device memory for the scratch it asks for)"]++; + ++skipped; ok = false; break; + } + r.scratch_bytes = need; + } + } + if (!ok) continue; /* the reason is already counted */ + if (world > 1) rad_dev_set(0); /* One geometry per candidate, built up front. As at issue, the chosen values are appended * to the resolved geometry, so a launch reads `sk` via rad_args_geti() like `M`. */ @@ -518,7 +708,7 @@ int main(int argc, char** argv) { std::vector best_us((size_t)n_var, -1.0), spread((size_t)n_var, 0.0); for (int v = 0; v < n_var; ++v) { double sp = 0; - best_us[(size_t)v] = time_point(*row, t, gv[(size_t)v], reps, iters, stream, &sp); + best_us[(size_t)v] = time_point(*row, rs, gv[(size_t)v], reps, iters, &sp); spread[(size_t)v] = sp; } @@ -530,7 +720,7 @@ int main(int argc, char** argv) { * kVariantTol allows the last-bit changes of a reordered reduction. */ std::vector ref; std::vector verr((size_t)n_var, 0.0); - if (best_us[0] <= 0 || capture_outputs(*row, t, gv[0], schema, sh, stream, &ref) < 0) { + if (best_us[0] <= 0 || capture_outputs(*row, rs, gv[0], schema, sh, &ref) < 0) { skip_why[tr.plugin + "/" + tr.kernel + " (the defaults refused the shape: no " "reference to check candidates against)"]++; ++skipped; @@ -539,7 +729,7 @@ int main(int argc, char** argv) { for (int v = 1; v < n_var; ++v) { if (best_us[(size_t)v] <= 0) continue; std::vector got; - if (capture_outputs(*row, t, gv[(size_t)v], schema, sh, stream, &got) < 0) { + if (capture_outputs(*row, rs, gv[(size_t)v], schema, sh, &got) < 0) { best_us[(size_t)v] = (double)RAD_E_STATE; continue; } @@ -589,8 +779,9 @@ int main(int argc, char** argv) { cache.put(tr_out); ++measured; - std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld)\n", op.c_str(), - tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space); + std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld%s)\n", op.c_str(), + tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space, + scale.c_str()); } if (dry) { @@ -607,8 +798,6 @@ int main(int argc, char** argv) { std::printf("\n%d request(s) had one point or none: nothing to choose, and the kernel's\n" "own axis defaults are already what it runs.\n", single); - rad_stream_destroy(stream); - cache.set_machine(machine); if (cache.save(save_home) < 0) return 1; From 1fb35740dfcf15d64080aef2633c4d994b45da61 Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 13:40:26 -0500 Subject: [PATCH 20/27] ple: an 8-chunk read-ahead queue with a sliced producer and a tunable row cache -- the table's rows prefetch off the step path --- arch/common/rad_block_ple.h | 18 ++++-- core/sched/batch.cpp | 25 +++++--- libavx/avx_ngram.cpp | 122 +++++++++++++++++++++++++++++++++--- tests/arch_test.cpp | 16 ++--- 4 files changed, 153 insertions(+), 28 deletions(-) diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index a09f2f78..446504fa 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -106,10 +106,18 @@ struct PleLayer { rad_op op_gate = 0, op_conv = 0, op_add = 0; int64_t hn() const { return c.hc * g.n_embd; } + /* The read-ahead queue's depth, in steps: the scheduler stages this many steps of the + * following prompt per step (batch.cpp, k_ahead_chunks) and the gather hands them to the + * reader thread, which prefetches their rows off the step path while the current chunk runs. + * Clamped to what `b_ids` was declared to hold, so a scheduler that offers more degrades the + * queue's depth, never an overflow. */ + static constexpr int64_t kAheadChunks = 8; /* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */ int64_t ahead_rows(const RadBatch* batch) const { const int64_t a = batch->n_ahead; - return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok); + if (a <= 0) return 0; + const int64_t cap = kAheadChunks * g.max_tok; + return a < cap ? a : cap; } int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer, @@ -275,10 +283,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C * follows declared order, where the two ops are adjacent, so a transient could be overwritten * in between. */ { - /* Twice the step's rows: the step's ids, then those of the prompt that follows - * (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */ + /* The step's rows, then the read-ahead queue's: up to kAheadChunks further steps of the + * following prompt (RadBatch::n_ahead), which the gather's reader prefetches while the + * step runs, so a prefill's table rows are read at disk speed off the step path. */ RadBufDecl d{}; - d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads; + d.dtype = RAD_I32; d.rank = 2; + d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads; d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST; b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d); diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 92becbe9..d21ab81a 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -12,6 +12,13 @@ namespace rad { +/* How many steps of the following prompt the PLE read-ahead queue stages (RadBatch::n_ahead): + * the arch's reader thread drains the queue at disk speed, off the step path, so a prefill + * chunk's table rows are already cached when its gather runs. Keep in step with rad_block_ple.h + * (kAheadChunks), which clamps to the buffer it declared; a mismatch degrades to a smaller queue, + * never an overflow. */ +static constexpr int64_t k_ahead_chunks = 8; + /* Alignment of each staging array carved from a set's slab. One slab per set means a couple of * allocations at init instead of two dozen, with every array sharing one mapping. */ static const int64_t k_carve_align = 256; @@ -97,9 +104,10 @@ void BatchBuilder::carve(Set& s, char* h) { *ph = ::rad::carve(h, oh, n); *pd = ::rad::carve(d, od, n); }; - /* Twice the step: its own tokens, then up to a step of the following prompt - * (RadBatch::n_ahead). */ - pair(&s.h_tok, &s.d_tok, 2 * T); + /* The step's tokens, then the PLE read-ahead queue -- k_ahead_chunks steps of the following + * prompt (RadBatch::n_ahead), which the arch's reader thread prefetches off the step path + * (rad_block_ple.h, which clamps to the same count). */ + pair(&s.h_tok, &s.d_tok, (1 + k_ahead_chunks) * T); pair(&s.h_pos, &s.d_pos, T); pair(&s.h_parent, &s.d_parent, T); pair(&s.h_cu, &s.d_cu, S + 1); @@ -1044,17 +1052,18 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, } } - /* Up to a step of the last sequence's following tokens, after this step's own - * (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by - * the tokens the request has; like token_at, a re-prefill after preemption continues into its - * own output. */ + /* Up to the read-ahead queue's worth of the last sequence's following tokens, after this + * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, + * bounded by the tokens the request has; like token_at, a re-prefill after preemption + * continues into its own output. The arch clamps to the rows it declared. */ int64_t n_ahead = 0; if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) { const StepEntry& e = plan.e[(size_t)(n_seq - 1)]; if (e.req && e.is_prefill) { const int64_t next = (int64_t)e.ctx_len + e.n_tokens; const int64_t have = (int64_t)e.req->prompt.size() + (int64_t)e.req->output.size(); - n_ahead = std::min(std::max(have - next, 0), max_tok_); + n_ahead = std::min(std::max(have - next, 0), + k_ahead_chunks * max_tok_); for (int64_t j = 0; j < n_ahead; ++j) s.h_tok[n_tok + j] = token_at(e, next + j); } } diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index ccb735d4..ae32f4ef 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -40,6 +40,7 @@ #include #include +#include #include #include #include @@ -60,6 +61,16 @@ namespace { +/* Phase timers for one rank's gather, when RAD_PLE_TIMING is set: accumulated on the issuing + * thread and printed by avx::row_gather. The ahead-reader thread accumulates and never prints. */ +struct PleTiming { + bool on = std::getenv("RAD_PLE_TIMING") != nullptr; + double find_ms = 0, pub_ms = 0, read_ms = 0, wait_ms = 0, dec_ms = 0, again_ms = 0; + uint64_t enters = 0, bytes = 0; + size_t spans = 0, hits = 0, claimed = 0, none = 0, theirs = 0; +}; +thread_local PleTiming t_ple; + /* Prefetch distance, in rows, for cache lookups and decodes. Rows are scattered over an 80 MiB * cache and the set words over 4 MiB, so each is an L3 or DRAM miss. */ constexpr long long kPrefetchRows = 8; @@ -281,7 +292,12 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) { * committed only as slots fill. */ struct RowCache { static constexpr int kWays = 8; - static constexpr uint64_t kRows = 1ull << 19; + /* Slot count, overridable with RAD_PLE_CACHE_ROWS (rows, clamped to [2^16, 2^25]). Data cost + * is `rows` * row bytes (160 at E4M3), so the shipped 2^19 rows is 80 MiB. The table's row + * popularity is Zipfian: a larger cache holds a longer hot head of the distribution and + * trades RAM directly for a lower miss rate on repeated traffic. Size it from measurement, + * not the model -- RAD_PLE_TIMING prints the per-call hit counts the sweep reads. */ + static const uint64_t kRows; enum : uint64_t { EMPTY = 0, LOADING = 1, READY = 2 }; const TableFile* tf = nullptr; @@ -361,6 +377,21 @@ T* anon_array(size_t count) { } /* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */ +/* Defined out of line so the environment is read once, at first use. */ +const uint64_t RowCache::kRows = [] { + unsigned long long v = 1ull << 19; + if (const char* s = std::getenv("RAD_PLE_CACHE_ROWS")) { + char* end = nullptr; + const long long n = std::strtoll(s, &end, 10); + if (end != s && n > 0) v = (uint64_t)n; + } + if (v < 1ull << 16) v = 1ull << 16; + if (v > 1ull << 25) v = 1ull << 25; + /* Whole sets: the set index is `mix(key) & set_mask` over kWays-way sets. */ + v -= v % kWays; + return v; +}(); + RowCache* row_cache(const TableFile* tf, long long n) { static std::mutex mu; static std::vector> caches; @@ -470,6 +501,16 @@ struct ReadRing { * one span per `stride` bytes, submitting and waiting in one call. Short reads fail. */ int read_spans(const TableFile& tf, const SpanRead* r, unsigned count, long long n, long long stride, uint8_t* bounce) { + if (!t_ple.on) return read_spans_now(tf, r, count, n, stride, bounce); + const auto t0 = std::chrono::steady_clock::now(); + const int s = read_spans_now(tf, r, count, n, stride, bounce); + t_ple.read_ms += + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + t_ple.spans += count; + return s; + } + int read_spans_now(const TableFile& tf, const SpanRead* r, unsigned count, long long n, + long long stride, uint8_t* bounce) { const long long A = tf.align; unsigned tail = __atomic_load_n(sq_tail, __ATOMIC_RELAXED); for (unsigned i = 0; i < count; ++i) { @@ -486,6 +527,7 @@ struct ReadRing { s->user_data = (uint64_t)(e - a); sq_array[idx] = idx; ++tail; + t_ple.bytes += (uint64_t)(e - a); } __atomic_store_n(sq_tail, tail, __ATOMIC_RELEASE); int status = RAD_OK; @@ -493,6 +535,7 @@ struct ReadRing { while (got < count) { const long rc = syscall(__NR_io_uring_enter, fd, to_submit, count - got, IORING_ENTER_GETEVENTS, nullptr, (size_t)0); + ++t_ple.enters; if (rc < 0 && errno != EINTR && errno != EAGAIN && errno != EBUSY) return RAD_E_IO; if (rc > 0) to_submit -= (unsigned)rc < to_submit ? (unsigned)rc : to_submit; unsigned h = __atomic_load_n(cq_head, __ATOMIC_RELAXED); @@ -620,6 +663,7 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.clear(); g.again.clear(); + const auto tf0 = std::chrono::steady_clock::now(); for (long long j = 0; j < M; ++j) { if (j + kPrefetchRows < M) { const long long mp = at(j + kPrefetchRows); @@ -632,17 +676,27 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG const RowCache::Found f = rc.find_or_claim(key, me, &s); g.slot[m] = s; g.kind[m] = (uint8_t)f; + if (f == RowCache::HIT) ++t_ple.hits; + else if (f == RowCache::CLAIMED) ++t_ple.claimed; + else if (f == RowCache::NONE) ++t_ple.none; + else if (f == RowCache::THEIRS) ++t_ple.theirs; if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s}); else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; } else if (f == RowCache::THEIRS) g.waits.push_back(m); } + t_ple.find_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + const auto tp0 = std::chrono::steady_clock::now(); int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tp0).count(); if (rs != RAD_OK) return rs; /* Wait for rows other threads claimed to turn READY. `published` is read before the words, so * a batch landing after the scan makes the wait return at once. Released claims (failed reads) * and reused slots are read by this thread instead. */ + const auto tw0 = std::chrono::steady_clock::now(); while (!g.waits.empty()) { const uint32_t e = rc.published.load(std::memory_order_acquire); size_t keep = 0; @@ -657,9 +711,12 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.resize(keep); if (keep) rc.published.wait(e, std::memory_order_acquire); } + t_ple.wait_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); /* Decode all READY rows in one batch: each word is read before the bytes and again after the * batch (the seqlock), and rows whose word changed are read again. */ + const auto td0 = std::chrono::steady_clock::now(); g.src.clear(); g.dst.clear(); g.dm.clear(); @@ -682,22 +739,35 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG for (size_t i = 0; i < g.dm.size(); ++i) if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) g.again.push_back(g.dm[i]); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); if (g.again.empty()) return RAD_OK; + const auto ta0 = std::chrono::steady_clock::now(); g.reads.clear(); for (long long m : g.again) g.reads.push_back({m, key_of(m), -1}); - return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.again_ms += + std::chrono::duration(std::chrono::steady_clock::now() - ta0).count(); + return ra; } /* ============================== the reader that runs a step ahead ============================== * * A prefill chunk gathers `heads` rows per token (32,768 for a 2048-token chunk); on unseen text * most are file reads (~30 ms per chunk on NVMe), during which the issuing thread waits and the card - * idles. The next chunk's ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so + * idles. The next chunks' ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so * the call hands them to one process-wide reader thread, which claims, reads and publishes the * missing rows while the chunk runs. The next call waits for LOADING rows as it would for the other * rank's. * + * The queue is handed over sliced: each job carries at most `kJobRows` keys, claimed and published + * one job at a time, in order. Claims are promises the consumer waits on (a slot LOADING for a row + * it needs blocks the gather on the reader's progress), so a job must stay small: bounded claims + * keep the promise horizon near, and a consumer that outruns the reader finds unclaimed rows it + * can read itself instead of waiting behind the whole queue. Jobs keep the list's order, so the + * nearest chunk's rows are always the reader's first work. + * * Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims * and the next call reads those rows itself. The reader is detached and never destroyed. */ struct AheadJob { @@ -707,6 +777,10 @@ struct AheadJob { std::vector keys; }; +/* One producer job's claim-read-publish sweep: ~2 ring batches, so the promise a job makes to a + * consuming gather is paid in well under a second on any disk that can stream the table. */ +constexpr size_t kJobRows = 8192; + struct AheadReader { std::mutex mu; std::condition_variable cv; @@ -726,6 +800,8 @@ struct AheadReader { q.pop_front(); } if (!rr || !me) continue; + const auto t0 = t_ple.on ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point(); g.reads.clear(); for (size_t i = 0; i < j.keys.size(); ++i) { if (i + kPrefetchRows < j.keys.size()) @@ -737,6 +813,12 @@ struct AheadReader { /* Every read has a slot, so nothing is decoded and there is no output. */ (void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr, nullptr, 0); + if (t_ple.on) { + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "ple[reader] keys %zu reads %zu %.1fms\n", j.keys.size(), + g.reads.size(), ms); + } } } }; @@ -750,7 +832,9 @@ AheadReader* ahead_reader() { return r; } -/* Hands the rows of `q.ahead` (to be gathered by a later call) to the reader. */ +/* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into + * `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so + * the nearest chunk's rows are its first work and a claim's promise horizon stays short. */ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc; for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; } @@ -760,17 +844,26 @@ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { if (h == r->last) return; r->last = h; } + const long long base = tf.off + (long long)(q.tab - tf.lo); AheadJob j; j.tf = &tf; j.rc = &rc; j.n = q.row_bytes; - const long long base = tf.off + (long long)(q.tab - tf.lo); - j.keys.reserve((size_t)q.n_ahead); + j.keys.reserve(kJobRows); for (long long m = 0; m < q.n_ahead; ++m) { const long long id = (long long)q.ahead[m] - q.voff; - if (id >= 0 && id < q.n_vocab) j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (id < 0 || id >= q.n_vocab) continue; + j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (j.keys.size() == kJobRows) { + { + std::lock_guard lk(r->mu); + r->q.push_back(j); + } + r->cv.notify_one(); + j.keys.clear(); + } } - { + if (!j.keys.empty()) { std::lock_guard lk(r->mu); r->q.push_back(std::move(j)); } @@ -806,6 +899,7 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { if (!tfile) return ferr; #if defined(__linux__) if (tfile->fd >= 0) { + const auto t0 = std::chrono::steady_clock::now(); int why = 0; ReadRing* rr = read_ring(&why); if (!rr) { @@ -819,6 +913,18 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0; const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut); if (rs != RAD_OK) return rs; + const double wall = + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (t_ple.on) + std::fprintf(stderr, + "ple[rank %lld] rows %lld: find %.1fms (hit %zu claimed %zu none %zu " + "theirs %zu) pub %.1fms (ring %.1fms, %llu enters, %zu spans, " + "%.1f MiB) wait %.1fms dec %.1fms again %.1fms | wall %.1fms\n", + (long long)q.rank, (long long)q.M, t_ple.find_ms, t_ple.hits, + t_ple.claimed, t_ple.none, t_ple.theirs, t_ple.pub_ms, t_ple.read_ms, + (unsigned long long)t_ple.enters, t_ple.spans, t_ple.bytes / 1048576.0, + t_ple.wait_ms, t_ple.dec_ms, t_ple.again_ms, wall); + t_ple = {}; /* Queue the rows a later call will gather, after this call's own rows. */ if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q); return RAD_OK; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 223ba77e..1d87c15b 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -8644,14 +8644,14 @@ struct ArchCases { qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); add("qwen4exp_fp8", [this](RadBuilder* b) { auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xbe74d476c7fd04b8ull); + qwen4exp_fp8::step, 3, {}, 0x43048d3448778280ull); add("qwen4exp_fp8, two ranks", [this](RadBuilder* b) { auto c = q4_ctx(0, 2); return qwen4exp_fp8::declare(b, &q4, &c); }, - nullptr, 3, { "ar_hc_write" }, 0x9d7df7914590d6d8ull); + nullptr, 3, { "ar_hc_write" }, 0x43d3be2b6d76e470ull); add("qwen4exp_fp8, four-bit experts", [this](RadBuilder* b) { b->encs = { { "ffn_gate_up_exps", w4 }, { "ffn_down_exps", w4 } }; auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xb308d06b168a61f1ull); + qwen4exp_fp8::step, 3, {}, 0x08d082fcbef37889ull); add("llama_fp8 + DSpark", [this](RadBuilder* b) { auto c = dspark_ctx(0, 1); return llama_fp8::declare(b, lla.meta(), &c); }, llama_fp8::step, 7, {}, 0xdcf36a1d31aba73cull); @@ -9333,11 +9333,11 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { uint64_t graph, steps; }; const Case cases[] = { - { "qwen4exp_fp8", 1, 0, 0x14b9cab0bea2591full, 0x26a9e2c23cf85696ull }, - { "qwen4exp_fp8", 2, 0, 0xc9bcbf1b538b597full, 0x889c6b36c014609full }, - { "qwen4exp_fp8", 2, 1, 0x8b2f1786a4ac12b8ull, 0x959ef6b7c6f57d8bull }, - { "qwen4exp_fp8", 4, 0, 0x1e97a26b759d29dfull, 0xfbe74f2b9d7020bfull }, - { "qwen4exp_fp8", 4, 3, 0x6669aa0573931943ull, 0x36df57cac613c6cfull }, + { "qwen4exp_fp8", 1, 0, 0x23ec76c443e2cb6full, 0x26a9e2c23cf85696ull }, + { "qwen4exp_fp8", 2, 0, 0x88290524cfd7714full, 0x889c6b36c014609full }, + { "qwen4exp_fp8", 2, 1, 0xa4268bda72739be8ull, 0x959ef6b7c6f57d8bull }, + { "qwen4exp_fp8", 4, 0, 0xaa5abead708b106full, 0xfbe74f2b9d7020bfull }, + { "qwen4exp_fp8", 4, 3, 0x9ffc4cf1b074a153ull, 0x36df57cac613c6cfull }, { "qwen35_fp8", 1, 0, 0xcfc82ca915ec549dull, 0x4d6fca823d1e97efull }, { "qwen35_fp8", 2, 1, 0xcaf28466af9e917dull, 0x0bcf5833fce11a86ull }, { "qwen35moe_fp8", 1, 0, 0x7fa7b015e1bc8873ull, 0x3fcf71676e558d79ull }, From d2d9b9687e850a46aeb79cf3a9f0fb6d501afba6 Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 14:31:25 -0500 Subject: [PATCH 21/27] ple: the gather defers all disk I/O to the producer -- the step thread classifies, waits per row on the producer's word, and never touches the ring --- libavx/avx_ngram.cpp | 251 ++++++++++++++++++++++++++++++------------- 1 file changed, 175 insertions(+), 76 deletions(-) diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index ae32f4ef..5b82014c 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -367,6 +367,28 @@ struct RowCache { /* The set changed between the scan and the claim: retry. */ } } + + /* Where `key` sits, without claiming it: READY in *slot (decode from it), LOADING in *slot + * (someone is reading it -- wait on the word), or ABSENT (*slot = -1; nobody has claimed the + * row, so whoever wants it must hand it to a producer or claim it themselves). */ + Found lookup(uint64_t key, int64_t* slot) const { + const uint64_t set = mix(key) & set_mask; + const uint64_t s0 = set * kWays; + for (int w = 0; w < kWays; ++w) { + const uint64_t x = word[s0 + w].load(std::memory_order_acquire); + if (x != EMPTY && (x >> 10) == key) { + *slot = (int64_t)(s0 + w); + return (x & 3) == READY ? HIT : THEIRS; + } + } + *slot = -1; + return NONE; + } + + /* Read batches that failed outright (the ring refused, the disk errored): the consumers + * waiting on those rows re-hand them to a producer, and this counter is how they notice that + * their wait has a cause. */ + std::atomic failed_reads{0}; }; template @@ -601,6 +623,9 @@ int ring_errno() { /* Reads `reads` through the ring in batches: rows with a slot are copied into the cache and * published READY; rows without one are decoded directly into their output rows. On a failed read, * every unpublished claim is released (word back to EMPTY) so no thread waits on it. */ +void ahead_urgent(const TableFile& tf, RowCache& rc, const std::vector& keys, + long long n); + int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, const std::vector& reads, long long n, long long ne, avx::RowDecode decode, const uint16_t* lut, uint16_t* out, long long x_ld) { @@ -612,6 +637,8 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, uint8_t* bounce = g.bounce_for((size_t)cnt * (size_t)stride, (size_t)A); const int rs = bounce ? rr.read_spans(tf, &reads[b], cnt, n, stride, bounce) : RAD_E_NOMEM; if (rs != RAD_OK) { + rc.failed_reads.fetch_add(1, std::memory_order_release); + rc.failed_reads.notify_all(); for (size_t i = b; i < total; ++i) if (reads[i].slot >= 0) rc.word[reads[i].slot].store(RowCache::EMPTY, std::memory_order_release); @@ -632,6 +659,9 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, std::memcpy(rc.data + (size_t)r.slot * (size_t)n, row, (size_t)n); rc.ref[r.slot].store(1, std::memory_order_relaxed); rc.word[r.slot].store(RowCache::ready(r.key), std::memory_order_release); + /* Per-slot wakeup: a consumer waiting on THIS row proceeds now, without waiting for + * the batch or the queue. Notify on a word nobody waits on costs a no-op futex wake. */ + rc.word[r.slot].notify_one(); } rc.published.fetch_add(1, std::memory_order_release); rc.published.notify_all(); @@ -641,11 +671,17 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, return RAD_OK; } -/* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row - * starting at row `first`, read this thread's claims, wait for rows other threads are reading, then - * decode from the cache. A row whose slot is taken over during the decode is read again directly. */ +/* out[m] = decoded row ids[m] - voff for every m < M, through the cache. This thread issues no + * file reads: every row is READY in the cache (decode from it), loading under a producer's claim + * (wait on its word -- the word is notified the moment the row lands), or claimed by nobody (the + * run is handed to the producer's urgent lane and waited on like the others). The drive serves one + * queue, at the full rate of one ring; the step thread never competes for it. + * + * The one fall from grace: a row whose cache slot is recycled while it waits (cache pressure from + * the run-ahead of later chunks) is re-handed to the producer's urgent lane, not read here. */ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, long long first, avx::RowDecode decode, const uint16_t* lut) { + (void)rr; Gather& g = gather_state(); const uint64_t me = owner_tag(); if (!me) return RAD_E_UNSUPPORTED; @@ -663,93 +699,113 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.clear(); g.again.clear(); + /* ---- classify without claiming. A row is READY (its slot decodes), loading under a + * producer's claim (its word is waited on), or absent -- nobody has claimed it, so its run is + * handed to the producer's urgent lane, ahead of the run-ahead queue. */ const auto tf0 = std::chrono::steady_clock::now(); + std::vector urgent; for (long long j = 0; j < M; ++j) { - if (j + kPrefetchRows < M) { - const long long mp = at(j + kPrefetchRows); - if (!pad(row_of(mp))) __builtin_prefetch(rc.set_line(key_of(mp))); - } const long long m = at(j); - if (pad(row_of(m))) { g.kind[m] = Gather::PAD; continue; } + uint16_t* dst = q.out + m * x_ld; + if (pad(row_of(m))) { + g.kind[m] = Gather::PAD; + std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); + continue; + } const uint64_t key = key_of(m); int64_t s = -1; - const RowCache::Found f = rc.find_or_claim(key, me, &s); - g.slot[m] = s; - g.kind[m] = (uint8_t)f; - if (f == RowCache::HIT) ++t_ple.hits; - else if (f == RowCache::CLAIMED) ++t_ple.claimed; - else if (f == RowCache::NONE) ++t_ple.none; - else if (f == RowCache::THEIRS) ++t_ple.theirs; - if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s}); - else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; } - else if (f == RowCache::THEIRS) g.waits.push_back(m); + const RowCache::Found f = rc.lookup(key, &s); + if (f == RowCache::HIT) { + g.slot[m] = s; + g.kind[m] = (uint8_t)RowCache::HIT; + ++t_ple.hits; + } else { + g.slot[m] = s; /* -1 when absent */ + if (f == RowCache::THEIRS) { g.kind[m] = (uint8_t)RowCache::THEIRS; ++t_ple.theirs; } + else { g.kind[m] = (uint8_t)Gather::DONE; urgent.push_back(key); + ++t_ple.none; } + } + /* Every row resolves through the wave loop below: READY rows decode in its first wave, + * the others wait on their producer and decode as they land. */ + g.waits.push_back(m); } t_ple.find_ms += std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + if (!urgent.empty()) ahead_urgent(tf, rc, urgent, n); - const auto tp0 = std::chrono::steady_clock::now(); - int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); - t_ple.pub_ms += - std::chrono::duration(std::chrono::steady_clock::now() - tp0).count(); - if (rs != RAD_OK) return rs; - - /* Wait for rows other threads claimed to turn READY. `published` is read before the words, so - * a batch landing after the scan makes the wait return at once. Released claims (failed reads) - * and reused slots are read by this thread instead. */ + /* ---- resolve. Each wave scans the open rows after a producer publish: READY rows decode in + * one batch (the seqlock word is read before the bytes and again after), LOADING rows keep + * waiting on their own word, rows whose slot moved on are re-handed to the urgent lane. */ const auto tw0 = std::chrono::steady_clock::now(); + size_t quiet = 0; while (!g.waits.empty()) { - const uint32_t e = rc.published.load(std::memory_order_acquire); + const uint64_t fails = rc.failed_reads.load(std::memory_order_acquire); + const uint32_t e = rc.published.load(std::memory_order_acquire); + g.src.clear(); + g.dst.clear(); + g.dm.clear(); + g.dw.clear(); size_t keep = 0; for (long long m : g.waits) { const uint64_t key = key_of(m); - const uint64_t x = rc.word[g.slot[m]].load(std::memory_order_acquire); - if (x == RowCache::ready(key)) continue; - if ((x & 3) == RowCache::LOADING && (x >> 10) == key) { g.waits[keep++] = m; continue; } - g.again.push_back(m); - g.kind[m] = Gather::DONE; + int64_t s = g.slot[m]; + if (s < 0 || ((rc.word[s].load(std::memory_order_acquire) & 3) != RowCache::READY + && (rc.word[s].load(std::memory_order_relaxed) >> 10) != key)) { + s = -1; + const RowCache::Found f = rc.lookup(key, &s); /* claimed/published since? */ + if (f == RowCache::HIT) { g.slot[m] = s; } + else if (f == RowCache::THEIRS) { g.slot[m] = s; g.kind[m] = (uint8_t)RowCache::THEIRS; } + else { g.slot[m] = -1; g.waits[keep++] = m; continue; } + } + const uint64_t w1 = rc.word[s].load(std::memory_order_acquire); + if (w1 == RowCache::ready(key)) { + g.src.push_back(rc.data + (size_t)s * (size_t)n); + g.dst.push_back(q.out + m * x_ld); + g.dm.push_back(m); + g.dw.push_back(w1); + continue; + } + if ((w1 & 3) == RowCache::LOADING && (w1 >> 10) == key) { + g.slot[m] = s; + g.kind[m] = (uint8_t)RowCache::THEIRS; + g.waits[keep++] = m; + continue; + } + /* The slot moved to another row: the read was lost. Hand it back. */ + g.slot[m] = -1; + g.kind[m] = (uint8_t)Gather::DONE; + urgent.push_back(key); + g.waits[keep++] = m; } g.waits.resize(keep); - if (keep) rc.published.wait(e, std::memory_order_acquire); + if (!g.src.empty()) { + decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); + std::atomic_thread_fence(std::memory_order_acquire); + for (size_t i = 0; i < g.dm.size(); ++i) + if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) { + g.slot[g.dm[i]] = -1; + g.kind[g.dm[i]] = (uint8_t)Gather::DONE; + urgent.push_back(key_of(g.dm[i])); + g.waits.push_back(g.dm[i]); + } + quiet = 0; + } else if (g.waits.size() == keep) { + ++quiet; + } + if (!g.waits.empty()) { + if (!urgent.empty()) { ahead_urgent(tf, rc, urgent, n); urgent.clear(); } + if (quiet > 64 && rc.failed_reads.load(std::memory_order_relaxed) > fails) { + /* The producer's reads are failing outright: waiting longer cannot help. */ + t_ple.wait_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); + return RAD_E_IO; + } + rc.published.wait(e, std::memory_order_acquire); + } } t_ple.wait_ms += std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); - - /* Decode all READY rows in one batch: each word is read before the bytes and again after the - * batch (the seqlock), and rows whose word changed are read again. */ - const auto td0 = std::chrono::steady_clock::now(); - g.src.clear(); - g.dst.clear(); - g.dm.clear(); - g.dw.clear(); - for (long long m = 0; m < M; ++m) { - uint16_t* dst = q.out + m * x_ld; - const uint8_t k = g.kind[m]; - if (k == Gather::PAD) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; } - if (k == Gather::DONE) continue; - const int64_t s = g.slot[m]; - const uint64_t w1 = rc.word[s].load(std::memory_order_acquire); - if (w1 != RowCache::ready(key_of(m))) { g.again.push_back(m); continue; } - g.src.push_back(rc.data + (size_t)s * (size_t)n); - g.dst.push_back(dst); - g.dm.push_back(m); - g.dw.push_back(w1); - } - if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); - std::atomic_thread_fence(std::memory_order_acquire); - for (size_t i = 0; i < g.dm.size(); ++i) - if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) - g.again.push_back(g.dm[i]); - t_ple.dec_ms += - std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); - - if (g.again.empty()) return RAD_OK; - const auto ta0 = std::chrono::steady_clock::now(); - g.reads.clear(); - for (long long m : g.again) g.reads.push_back({m, key_of(m), -1}); - const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); - t_ple.again_ms += - std::chrono::duration(std::chrono::steady_clock::now() - ta0).count(); - return ra; + return RAD_OK; } /* ============================== the reader that runs a step ahead ============================== @@ -784,7 +840,8 @@ constexpr size_t kJobRows = 8192; struct AheadReader { std::mutex mu; std::condition_variable cv; - std::deque q; + std::deque urgent; /* a waiting consumer's own misses: served first */ + std::deque q; /* the run-ahead queue: future chunks, in order */ uint64_t last = 0; /* hash of the last id list accepted */ void run() { @@ -795,24 +852,37 @@ struct AheadReader { AheadJob j; { std::unique_lock lk(mu); - cv.wait(lk, [&] { return !q.empty(); }); - j = std::move(q.front()); - q.pop_front(); + cv.wait(lk, [&] { return !urgent.empty() || !q.empty(); }); + if (!urgent.empty()) { j = std::move(urgent.front()); urgent.pop_front(); } + else { j = std::move(q.front()); q.pop_front(); } } if (!rr || !me) continue; const auto t0 = t_ple.on ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point(); g.reads.clear(); + std::vector retry; /* sets full of LOADING: claim again after a wave */ for (size_t i = 0; i < j.keys.size(); ++i) { if (i + kPrefetchRows < j.keys.size()) __builtin_prefetch(j.rc->set_line(j.keys[i + kPrefetchRows])); int64_t slot = -1; - if (j.rc->find_or_claim(j.keys[i], me, &slot) == RowCache::CLAIMED) + const auto f = j.rc->find_or_claim(j.keys[i], me, &slot); + if (f == RowCache::CLAIMED) g.reads.push_back({0, j.keys[i], slot}); + else if (f == RowCache::NONE) + retry.push_back(j.keys[i]); + /* READY/HIT: already there (a rank's gather, or an earlier pass). MINE: ours + * from an earlier pass -- published when its read lands. */ } /* Every read has a slot, so nothing is decoded and there is no output. */ (void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr, nullptr, 0); + if (!retry.empty()) { + std::lock_guard lk(mu); + AheadJob r; + r.tf = j.tf; r.rc = j.rc; r.n = j.n; r.keys = std::move(retry); + urgent.push_front(std::move(r)); + cv.notify_one(); + } if (t_ple.on) { const double ms = std::chrono::duration( std::chrono::steady_clock::now() - t0).count(); @@ -832,6 +902,35 @@ AheadReader* ahead_reader() { return r; } +/* Hands a waiting consumer's own misses to the reader's urgent lane: sliced like the run-ahead + * queue, served ahead of it. A key the reader finds already READY costs nothing; one it claims is + * read at the full rate of a single ring -- the consumer never competes for the disk. */ +void ahead_urgent(const TableFile& tf, RowCache& rc, const std::vector& keys, + long long n) { + AheadReader* r = ahead_reader(); + AheadJob j; + j.tf = &tf; + j.rc = &rc; + j.n = n; + j.keys.reserve(kJobRows); + for (uint64_t key : keys) { + j.keys.push_back(key); + if (j.keys.size() == kJobRows) { + { + std::lock_guard lk(r->mu); + r->urgent.push_back(j); + } + r->cv.notify_one(); + j.keys.clear(); + } + } + if (!j.keys.empty()) { + std::lock_guard lk(r->mu); + r->urgent.push_back(std::move(j)); + } + r->cv.notify_one(); +} + /* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into * `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so * the nearest chunk's rows are its first work and a claim's promise horizon stays short. */ From 2078b28fcbf98d62fe0ca96d7a1b5acc2a2bd817 Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 15:26:01 -0500 Subject: [PATCH 22/27] tune: --max-seqs, --kv-cache-dtype, --tp-wire, --tp-wire-min-kb -- declare at the served configuration, or the tune rows key to bands no served step selects --- tools/rad_tune.cpp | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tools/rad_tune.cpp b/tools/rad_tune.cpp index d74bf679..bcb7ede8 100644 --- a/tools/rad_tune.cpp +++ b/tools/rad_tune.cpp @@ -45,8 +45,14 @@ void usage() { " --iters N launches per rep (default 32). One launch is short enough that\n" " launch overhead and clock ramp would otherwise dominate.\n" " --max-tok N the max_tok declare is run at (default 8192)\n" + " --max-seqs N the max_seqs declare is run at (default 256)\n" " --tp N tensor-parallel width to declare at (default 1). The shapes a\n" " sharded deployment runs are not the shapes tp=1 runs.\n" + " --kv-cache-dtype T bf16 (default) or fp8 -- attention bands are gated on it.\n" + " Declare what the served engine runs, or the tune rows will not\n" + " match the bands it selects.\n" + " --tp-wire MODE exact (default) or wht6 -- selects the all-reduce family.\n" + " --tp-wire-min-kb N the message size from which the lossy wire is used.\n" " --num-speculative-tokens N|auto\n" " draft depth to declare at (default auto: the container's own). It puts\n" " the drafter's kernels in the measured graph.\n" @@ -335,7 +341,11 @@ int main(int argc, char** argv) { std::vector hierarchy = rad_hierarchy_from_env(); int reps = 5, iters = 32; int64_t max_tok = 8192; + int64_t max_seqs = 256; int tp = 1, spec = -1; /* -1 = the container's own drafter depth */ + int kv_dtype = RAD_DT_INVALID; /* RAD_F8E4M3 = the engine's --kv-cache-dtype fp8 */ + int wire_lossy = 0; /* the engine's --tp-wire wht6 */ + int64_t wire_min_kb = 128; /* the engine's --tp-wire-min-kb */ bool dry = false, verbose = false; for (int i = 1; i < argc; ++i) { @@ -357,7 +367,24 @@ int main(int argc, char** argv) { else if (a == "--reps") reps = (int)num("--reps", 1, INT32_MAX); else if (a == "--iters") iters = (int)num("--iters", 1, INT32_MAX); else if (a == "--max-tok") max_tok = num("--max-tok", 1, INT64_MAX); + else if (a == "--max-seqs") max_seqs = num("--max-seqs", 1, INT64_MAX); else if (a == "--tp") tp = (int)num("--tp", 1, INT32_MAX); + else if (a == "--kv-cache-dtype") { + const char* v = next("--kv-cache-dtype"); + if (!std::strcmp(v, "fp8")) kv_dtype = RAD_F8E4M3; + else if (!std::strcmp(v, "bf16")) kv_dtype = RAD_DT_INVALID; + else { std::fprintf(stderr, "rad-tune: --kv-cache-dtype: '%s' is not one of " + "bf16, fp8 (the tuner tunes the bands it declares; other " + "encodings are the engine's)\n", v); return 2; } + } + else if (a == "--tp-wire") { + const char* v = next("--tp-wire"); + if (!std::strcmp(v, "wht6")) wire_lossy = 1; + else if (!std::strcmp(v, "exact")) wire_lossy = 0; + else { std::fprintf(stderr, "rad-tune: --tp-wire: '%s' is not one of exact, wht6\n", + v); return 2; } + } + else if (a == "--tp-wire-min-kb") wire_min_kb = num("--tp-wire-min-kb", 0, INT64_MAX); else if (a == "--num-speculative-tokens") { /* `auto` is the container's own depth, as the engine's flag of this name reads it. */ const char* v = next("--num-speculative-tokens"); @@ -410,10 +437,14 @@ int main(int argc, char** argv) { * the speculative depth decides whether the drafter (and its shapes) is in the graph. */ RadBuildCtx ctx{}; ctx.rank = 0; ctx.world_size = tp; ctx.max_tok = max_tok; + ctx.max_seqs = max_seqs; + ctx.tp_wire_lossy = wire_lossy; + ctx.tp_wire_min_bytes = wire_min_kb * 1024; + ctx.kv_dtype = kv_dtype; RadArchProbe probe{}; (void)rad_tools_probe(plugins, meta, &probe); ctx.max_spec = spec >= 0 ? spec : probe.draft_depth; - ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = ""; + ctx.max_seqs = max_seqs; ctx.max_ctx = meta.n_ctx_train; ctx.scope = ""; /* Peer access, measured before selection, as Engine does: collectives constrain device.p2p * (abi/rad_types.h), and with the fact unset neither the peer-to-peer row nor its host-memory From 2918a2eef26b4bcbe0bb255241eea272c074fb8e Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 16:21:04 -0500 Subject: [PATCH 23/27] sched: re-record the pinned step-batch fingerprints -- the read-ahead queue stages 9T tokens, not 2 --- tests/sched_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index d6d32d62..a039004e 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -5661,8 +5661,8 @@ uint64_t scripted_steps(int64_t max_tok, int64_t interval, int64_t busy, int* n_ TEST(without_a_span_the_scheduler_plans_and_stages_the_pinned_steps) { struct Case { int64_t max_tok, interval, busy; uint64_t want; }; const Case cases[] = { - { 256, 256, -1, 0x17b8231a20db9d46ull }, { 512, 256, -1, 0xe155e72b6a4cc94full }, { 1024, 256, -1, 0x54ba52dac3f4f61cull }, - { 1024, 256, 0, 0x54ba52dac3f4f61cull }, { 1024, 256, 128, 0x3d9cbbf533e3c4b5ull }, { 2048, 512, -1, 0x400205b7b9afcf12ull }, + { 256, 256, -1, 0x9b2fe92b1919355cull }, { 512, 256, -1, 0xdae73489249b5339ull }, { 1024, 256, -1, 0x44975a352e78619aull }, + { 1024, 256, 0, 0x44975a352e78619aull }, { 1024, 256, 128, 0x3c0b9b1a1f864e4aull }, { 2048, 512, -1, 0xd6c184d0563159eeull }, }; for (const Case& c : cases) { int n = 0; From baf503e021933c9f1a03b8f6a59e5d0309283ca1 Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 17:07:05 -0500 Subject: [PATCH 24/27] ple: the gather self-produces unclaimed rows on decode -- the queue prefetches prefill futures only; a decode step never waits behind it --- libavx/avx_ngram.cpp | 200 +++++++++++++++---------------------------- 1 file changed, 71 insertions(+), 129 deletions(-) diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index 5b82014c..68ecc669 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -623,9 +623,6 @@ int ring_errno() { /* Reads `reads` through the ring in batches: rows with a slot are copied into the cache and * published READY; rows without one are decoded directly into their output rows. On a failed read, * every unpublished claim is released (word back to EMPTY) so no thread waits on it. */ -void ahead_urgent(const TableFile& tf, RowCache& rc, const std::vector& keys, - long long n); - int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, const std::vector& reads, long long n, long long ne, avx::RowDecode decode, const uint16_t* lut, uint16_t* out, long long x_ld) { @@ -671,17 +668,11 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, return RAD_OK; } -/* out[m] = decoded row ids[m] - voff for every m < M, through the cache. This thread issues no - * file reads: every row is READY in the cache (decode from it), loading under a producer's claim - * (wait on its word -- the word is notified the moment the row lands), or claimed by nobody (the - * run is handed to the producer's urgent lane and waited on like the others). The drive serves one - * queue, at the full rate of one ring; the step thread never competes for it. - * - * The one fall from grace: a row whose cache slot is recycled while it waits (cache pressure from - * the run-ahead of later chunks) is re-handed to the producer's urgent lane, not read here. */ +/* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row + * starting at row `first`, read this thread's claims, wait for rows other threads are reading, then + * decode from the cache. A row whose slot is taken over during the decode is read again directly. */ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, long long first, avx::RowDecode decode, const uint16_t* lut) { - (void)rr; Gather& g = gather_state(); const uint64_t me = owner_tag(); if (!me) return RAD_E_UNSUPPORTED; @@ -699,113 +690,93 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.clear(); g.again.clear(); - /* ---- classify without claiming. A row is READY (its slot decodes), loading under a - * producer's claim (its word is waited on), or absent -- nobody has claimed it, so its run is - * handed to the producer's urgent lane, ahead of the run-ahead queue. */ const auto tf0 = std::chrono::steady_clock::now(); - std::vector urgent; for (long long j = 0; j < M; ++j) { - const long long m = at(j); - uint16_t* dst = q.out + m * x_ld; - if (pad(row_of(m))) { - g.kind[m] = Gather::PAD; - std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); - continue; + if (j + kPrefetchRows < M) { + const long long mp = at(j + kPrefetchRows); + if (!pad(row_of(mp))) __builtin_prefetch(rc.set_line(key_of(mp))); } + const long long m = at(j); + if (pad(row_of(m))) { g.kind[m] = Gather::PAD; continue; } const uint64_t key = key_of(m); int64_t s = -1; - const RowCache::Found f = rc.lookup(key, &s); - if (f == RowCache::HIT) { - g.slot[m] = s; - g.kind[m] = (uint8_t)RowCache::HIT; - ++t_ple.hits; - } else { - g.slot[m] = s; /* -1 when absent */ - if (f == RowCache::THEIRS) { g.kind[m] = (uint8_t)RowCache::THEIRS; ++t_ple.theirs; } - else { g.kind[m] = (uint8_t)Gather::DONE; urgent.push_back(key); - ++t_ple.none; } - } - /* Every row resolves through the wave loop below: READY rows decode in its first wave, - * the others wait on their producer and decode as they land. */ - g.waits.push_back(m); + const RowCache::Found f = rc.find_or_claim(key, me, &s); + g.slot[m] = s; + g.kind[m] = (uint8_t)f; + if (f == RowCache::HIT) ++t_ple.hits; + else if (f == RowCache::CLAIMED) ++t_ple.claimed; + else if (f == RowCache::NONE) ++t_ple.none; + else if (f == RowCache::THEIRS) ++t_ple.theirs; + if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s}); + else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; } + else if (f == RowCache::THEIRS) g.waits.push_back(m); } t_ple.find_ms += std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); - if (!urgent.empty()) ahead_urgent(tf, rc, urgent, n); - /* ---- resolve. Each wave scans the open rows after a producer publish: READY rows decode in - * one batch (the seqlock word is read before the bytes and again after), LOADING rows keep - * waiting on their own word, rows whose slot moved on are re-handed to the urgent lane. */ + const auto tp0 = std::chrono::steady_clock::now(); + int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tp0).count(); + if (rs != RAD_OK) return rs; + + /* Wait for rows other threads claimed to turn READY. `published` is read before the words, so + * a batch landing after the scan makes the wait return at once. Released claims (failed reads) + * and reused slots are read by this thread instead. */ const auto tw0 = std::chrono::steady_clock::now(); - size_t quiet = 0; while (!g.waits.empty()) { - const uint64_t fails = rc.failed_reads.load(std::memory_order_acquire); - const uint32_t e = rc.published.load(std::memory_order_acquire); - g.src.clear(); - g.dst.clear(); - g.dm.clear(); - g.dw.clear(); + const uint32_t e = rc.published.load(std::memory_order_acquire); size_t keep = 0; for (long long m : g.waits) { const uint64_t key = key_of(m); - int64_t s = g.slot[m]; - if (s < 0 || ((rc.word[s].load(std::memory_order_acquire) & 3) != RowCache::READY - && (rc.word[s].load(std::memory_order_relaxed) >> 10) != key)) { - s = -1; - const RowCache::Found f = rc.lookup(key, &s); /* claimed/published since? */ - if (f == RowCache::HIT) { g.slot[m] = s; } - else if (f == RowCache::THEIRS) { g.slot[m] = s; g.kind[m] = (uint8_t)RowCache::THEIRS; } - else { g.slot[m] = -1; g.waits[keep++] = m; continue; } - } - const uint64_t w1 = rc.word[s].load(std::memory_order_acquire); - if (w1 == RowCache::ready(key)) { - g.src.push_back(rc.data + (size_t)s * (size_t)n); - g.dst.push_back(q.out + m * x_ld); - g.dm.push_back(m); - g.dw.push_back(w1); - continue; - } - if ((w1 & 3) == RowCache::LOADING && (w1 >> 10) == key) { - g.slot[m] = s; - g.kind[m] = (uint8_t)RowCache::THEIRS; - g.waits[keep++] = m; - continue; - } - /* The slot moved to another row: the read was lost. Hand it back. */ - g.slot[m] = -1; - g.kind[m] = (uint8_t)Gather::DONE; - urgent.push_back(key); - g.waits[keep++] = m; + const uint64_t x = rc.word[g.slot[m]].load(std::memory_order_acquire); + if (x == RowCache::ready(key)) continue; + if ((x & 3) == RowCache::LOADING && (x >> 10) == key) { g.waits[keep++] = m; continue; } + g.again.push_back(m); + g.kind[m] = Gather::DONE; } g.waits.resize(keep); - if (!g.src.empty()) { - decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); - std::atomic_thread_fence(std::memory_order_acquire); - for (size_t i = 0; i < g.dm.size(); ++i) - if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) { - g.slot[g.dm[i]] = -1; - g.kind[g.dm[i]] = (uint8_t)Gather::DONE; - urgent.push_back(key_of(g.dm[i])); - g.waits.push_back(g.dm[i]); - } - quiet = 0; - } else if (g.waits.size() == keep) { - ++quiet; - } - if (!g.waits.empty()) { - if (!urgent.empty()) { ahead_urgent(tf, rc, urgent, n); urgent.clear(); } - if (quiet > 64 && rc.failed_reads.load(std::memory_order_relaxed) > fails) { - /* The producer's reads are failing outright: waiting longer cannot help. */ - t_ple.wait_ms += - std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); - return RAD_E_IO; - } - rc.published.wait(e, std::memory_order_acquire); - } + if (keep) rc.published.wait(e, std::memory_order_acquire); } t_ple.wait_ms += std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); - return RAD_OK; + + /* Decode all READY rows in one batch: each word is read before the bytes and again after the + * batch (the seqlock), and rows whose word changed are read again. */ + const auto td0 = std::chrono::steady_clock::now(); + g.src.clear(); + g.dst.clear(); + g.dm.clear(); + g.dw.clear(); + for (long long m = 0; m < M; ++m) { + uint16_t* dst = q.out + m * x_ld; + const uint8_t k = g.kind[m]; + if (k == Gather::PAD) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; } + if (k == Gather::DONE) continue; + const int64_t s = g.slot[m]; + const uint64_t w1 = rc.word[s].load(std::memory_order_acquire); + if (w1 != RowCache::ready(key_of(m))) { g.again.push_back(m); continue; } + g.src.push_back(rc.data + (size_t)s * (size_t)n); + g.dst.push_back(dst); + g.dm.push_back(m); + g.dw.push_back(w1); + } + if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); + std::atomic_thread_fence(std::memory_order_acquire); + for (size_t i = 0; i < g.dm.size(); ++i) + if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) + g.again.push_back(g.dm[i]); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); + + if (g.again.empty()) return RAD_OK; + const auto ta0 = std::chrono::steady_clock::now(); + g.reads.clear(); + for (long long m : g.again) g.reads.push_back({m, key_of(m), -1}); + const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.again_ms += + std::chrono::duration(std::chrono::steady_clock::now() - ta0).count(); + return ra; } /* ============================== the reader that runs a step ahead ============================== @@ -902,35 +873,6 @@ AheadReader* ahead_reader() { return r; } -/* Hands a waiting consumer's own misses to the reader's urgent lane: sliced like the run-ahead - * queue, served ahead of it. A key the reader finds already READY costs nothing; one it claims is - * read at the full rate of a single ring -- the consumer never competes for the disk. */ -void ahead_urgent(const TableFile& tf, RowCache& rc, const std::vector& keys, - long long n) { - AheadReader* r = ahead_reader(); - AheadJob j; - j.tf = &tf; - j.rc = &rc; - j.n = n; - j.keys.reserve(kJobRows); - for (uint64_t key : keys) { - j.keys.push_back(key); - if (j.keys.size() == kJobRows) { - { - std::lock_guard lk(r->mu); - r->urgent.push_back(j); - } - r->cv.notify_one(); - j.keys.clear(); - } - } - if (!j.keys.empty()) { - std::lock_guard lk(r->mu); - r->urgent.push_back(std::move(j)); - } - r->cv.notify_one(); -} - /* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into * `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so * the nearest chunk's rows are its first work and a claim's promise horizon stays short. */ From cc0a862afa39d010eee3dff4c620bbe83219d5ff Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 17:15:42 -0500 Subject: [PATCH 25/27] ple: two gather regimes -- decode gathers on demand (lookup or direct read, no queue, no claims); prefill chunks use the producer queue --- libavx/avx_ngram.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index 68ecc669..66e2bb4f 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -668,11 +668,64 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, return RAD_OK; } +/* The on-demand regime: decode steps want a hundred-odd rows now. The session's hot rows are + * READY in the cache and decode from it; anything else is read straight from the file into its + * output row -- no claims, no eviction bookkeeping, no queue round trip, no waiting on anybody. + * Misses read here are deliberately not cached: the chunked prefill before decode has already + * cached the prompt's rows, and a decode step's occasional new trigram is not worth a claim. */ +constexpr long long kOnDemandMaxRows = 4096; + +int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, + avx::RowDecode decode, const uint16_t* lut) { + Gather& g = gather_state(); + const long long M = q.M, n = q.row_bytes, ne = q.n_embd, x_ld = q.x_ld; + const long long base = tf.off + (long long)(q.tab - tf.lo); + auto row_of = [&](long long m) { return (long long)q.ids[m] - q.voff; }; + auto pad = [&](long long id) { return id < 0 || id >= q.n_vocab; }; + auto key_of = [&](long long m) { return (uint64_t)(base + row_of(m) * n); }; + + g.src.clear(); + g.dst.clear(); + g.reads.clear(); + const auto tf0 = std::chrono::steady_clock::now(); + for (long long m = 0; m < M; ++m) { + uint16_t* dst = q.out + m * x_ld; + if (pad(row_of(m))) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; } + const uint64_t key = key_of(m); + int64_t s = -1; + if (rc.lookup(key, &s) == RowCache::HIT) { + g.src.push_back(rc.data + (size_t)s * (size_t)n); + g.dst.push_back(dst); + ++t_ple.hits; + continue; + } + g.reads.push_back({m, key, -1}); /* direct read, no claim */ + ++t_ple.none; + } + t_ple.find_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + if (!g.reads.empty()) { + const auto tr0 = std::chrono::steady_clock::now(); + const int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tr0).count(); + if (rs != RAD_OK) return rs; + } + const auto td0 = std::chrono::steady_clock::now(); + if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); + return RAD_OK; +} + /* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row * starting at row `first`, read this thread's claims, wait for rows other threads are reading, then * decode from the cache. A row whose slot is taken over during the decode is read again directly. */ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, long long first, avx::RowDecode decode, const uint16_t* lut) { + /* Two regimes. A decode step wants a hundred-odd rows now: on-demand, direct, no queue. A + * prefill chunk wants tens of thousands and has a known future: the producer-consumer queue. */ + if (q.M <= kOnDemandMaxRows) return gather_ondemand(tf, rc, rr, q, decode, lut); Gather& g = gather_state(); const uint64_t me = owner_tag(); if (!me) return RAD_E_UNSUPPORTED; From 32bb5592d0d95252b242073b37dce34e80624fe5 Mon Sep 17 00:00:00 2001 From: Dustin Ewan Date: Fri, 23 Oct 2026 19:54:26 -0500 Subject: [PATCH 26/27] engine: a stall watch across the step loop -- a frozen step reports the blocked thread, its syscall and its stack instead of hanging silently --- core/engine.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/engine.cpp b/core/engine.cpp index 317f6ede..2bfaa966 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -413,6 +413,10 @@ int Engine::step_loop() { /* The next step's forward pass when already issued behind the previous step, before its * readback (Scheduler::step_next). */ const RadBatch* ahead = nullptr; + /* Names where the step loop waits when nothing has been logged for a while: a freeze reports + * the blocked thread, its syscall and its stack; long quiet generations report sparsely (the + * silence doubles) and the reports read as the ordinary GPU wait. */ + rad::StallWatch step_watch("step", 20000); while (!stopping_.load(std::memory_order_acquire)) { lora_epoch_.fetch_add(1, std::memory_order_acq_rel); phase_t_ = std::chrono::steady_clock::now(); From 6efffe2a590a8ae4c02c9e6fae790a16806f3704 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 25 Oct 2026 10:03:33 +0100 Subject: [PATCH 27/27] libr4d: the split-KV decode attention (head 256, gqa 6) stages V4 without bank conflicts or serial rounds The V4 tile's store (storeV4) wrote dim octets 8 rows = 96 dwords apart, so the octets a wave stores at once shared banks (4-way on 32 banks), and on k6_v4 each tile's V fetch ran as three exec-masked rounds, each issued after the previous one returned, the scale pair packed right after its loads. Now: - the V tile is skewed: octet o's rows start 16 (o & 3) + 8 ((o >> 2) & 1) + 128 (o >> 2) halfwords later, so a store's octets land on distinct banks; the PV read adds the same offset, a compile-time constant a fragment (V4 at tile 16, contiguous layout, two or more waves; one wave keeps the plain tile, which its LDS budget needs); - k6_v4: __builtin_assume(tid < NTHR) and a wave-uniform test for the partial round, so a tile's V loads issue as one batch, and the scale pair packed at the store, as the prefill kernel does since its own fix. fp8_v4 keeps the tested rounds (batched there, its 4-row steps ran 6 % slower) and its pack. Bit for bit: the same values in the same LDS cells, read in the same order. r4d_selftest --perfdecattn on 2x R9700 (265 W), Qwen3.8-27B TP2 rank, k6_v4, sequences x rows x context, 3 interleaved rounds, medians: 1x8x100k 277.0 -> 260.1 us (-6.1 %), 1x8x200k 404.8 -> 377.7 (-6.7 %), 4x8x100k 799.4 -> 753.0 (-5.8 %), 4x8x200k 1733.3 -> 1655.3 (-4.5 %), 8x4x100k 1257.8 -> 1179.8 (-6.2 %), 16x4x41k 996.3 -> 973.4 (-2.3 %). fp8_v4 with the skew alone: -3.6 % (16x4x41k) .. -0.1 %. Co-Authored-By: Claude Opus 5.5 (1M context) --- libr4d/r4d_attn_decode_h256_gqa6.hip | 48 ++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index ccbeb03b..3371b952 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -132,13 +132,25 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) constexpr float PGROW = D::GROW; __shared__ uint16_t sK[KLDS ? TILE * KSTR : 1]; - __shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR]; + // V4 at TILE 16: dim octet o's 8 rows start S(o) = 16 (o & 3) + 8 ((o >> 2) & 1) + 128 (o >> 2) + // halfwords later, so the 4 (8) octets of a storeV4 store land on distinct banks (unskewed they + // share them: 8 rows = 96 dwords = 0 mod 32). The 128 (o >> 2) term (64 dwords, unseen by the + // banks) keeps octet o's last row clear of octet o + 1's first; multiples of 8 halfwords keep the + // b128 PV read aligned. NWARPS 1 keeps the plain tile: its 10 workgroups a WGP would not fit. + constexpr int VSK = (V4 && TILE == 16 && CTG && NWARPS >= 2) ? 1 : 0; + constexpr int VSKN = HEAD_DIM / 8 - 1; + constexpr int VSKX = VSK ? 16 * (VSKN & 3) + 8 * ((VSKN >> 2) & 1) + 128 * (VSKN >> 2) : 0; + __shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR + VSKX]; /* A code-tile row is 16 keys + 8 padding = 24 bytes (six dwords): the sixteen lanes of a * fragment read hit distinct banks, and a lane's eight codes are one aligned 8-byte load. */ constexpr int VSTR8 = TILE + 8; __shared__ uint8_t sV8[V8 ? HEAD_DIM * VSTR8 : 1]; const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + // The launch is NTHR threads. Stated (k6_v4), so the V4 rounds wholly below NP4 lose their range + // test: as exec-masked blocks, each round's loads issued only after the previous round's returned. + // fp8_v4 keeps the tested rounds: batched there, its 4-row steps ran 6 % slower. + if constexpr (K6) __builtin_assume(tid < NTHR); const int c = lane & 15, h = lane >> 4; const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z; @@ -219,12 +231,19 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) // scale, widened with packed f16 into one dword a dim), fetched in the tile: no prefetch. constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8); constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1; - uint32_t v4c[U4][2], v4s[U4]; + // The pair's two scales stay apart until storeV4 packs them: packed here, the fetch is waited on + // right after it is issued. fp8_v4 packs here as before, as the prefill kernel keeps it. + constexpr int OLDV4 = V4 && !K6; + uint32_t v4c[U4][2], v4s[U4][2]; auto fetchV4 = [&](int k0, const int* blks) { #pragma unroll for (int r = 0; r < U4; ++r) { const int u = tid + r * NTHR; - if (NP4 % NTHR == 0 || u < NP4) { + // k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR) + // / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch. + if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4 + || (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR + : u < NP4)) : u < NP4)) { const int kp = u % (TILE / 2), o = u / (TILE / 2); uint32_t sc[2]; #pragma unroll @@ -237,7 +256,8 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4); sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2); } - v4s[r] = sc[0] | (sc[1] << 16); + if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; } + else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; } } } }; @@ -246,16 +266,21 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) #pragma unroll for (int r = 0; r < U4; ++r) { const int u = tid + r * NTHR; - if (NP4 % NTHR == 0 || u < NP4) { + // k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR) + // / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch. + if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4 + || (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR + : u < NP4)) : u < NP4)) { const int kp = u % (TILE / 2), o = u / (TILE / 2); // Two's complement nibbles; ^ 8 makes them offset binary (value + 8). const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u; const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u; const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; - const h2 s2 = __builtin_bit_cast(h2, v4s[r]); + const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16))); const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f }; - uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp]; + uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp + + (VSK ? 16 * (o & 3) + 8 * ((o >> 2) & 1) + 128 * (o >> 2) : 0)]; #pragma unroll for (int b = 0; b < 4; ++b) { const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u; @@ -507,13 +532,18 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) const uint2 y = swap16_u2p((h == 0) ? hi2 : lo); p16 = (h == 0) ? D::mk(lo, y) : D::mk(y, hi2); } - const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0); + // Skewed tile: row 16 G + c is in octet 2 G + (c >> 3), so its S is 16 (c >> 3) here + // plus 32 (G & 1) + 8 ((G >> 1) & 1) + 128 (G >> 1), a compile-time offset below. + const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0) + + (VSK ? 16 * (c >> 3) : 0); #pragma unroll for (int g = 0; g < NKS; g += PF) { frag16 vb[PF]; #pragma unroll for (int j = 0; j < PF; ++j) { - const uint16_t* vp = vbase + (g + j) * 16 * VSTR; + const uint16_t* vp = vbase + (g + j) * 16 * VSTR + + (VSK ? 32 * ((g + j) & 1) + 8 * (((g + j) >> 1) & 1) + 128 * ((g + j) >> 1) + : 0); if (V8) { uint32_t w4[4]; fp8x8_to_16x4w(*(const uint2*)&sV8[(c + (g + j) * 16) * VSTR8 +